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

The following examples show how to use org.kie.api.runtime.KieSession#setGlobal() . 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: JTMSTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testConflictStrict() {
    KieSession kSession = getSessionFromFile( "posNegConflict.drl" );

    ArrayList list = new ArrayList();
    kSession.setGlobal( "list", list );

    
    NamedEntryPoint ep = ( NamedEntryPoint ) ((StatefulKnowledgeSessionImpl)kSession).getEntryPoint( "DEFAULT" );
    JTMSBeliefSystem bs = ( JTMSBeliefSystem ) ep.getTruthMaintenanceSystem().getBeliefSystem();
    bs.STRICT = true;

    try {
        kSession.fireAllRules();
        fail( "A fact and its negation should have been asserted, but no exception was trhown in strict mode" );
    } catch ( Exception e ) {
    } finally {
        bs.STRICT = false;
    }
}
 
Example 2
Source File: EventAccessorRestoreTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeserialization() {
    try {
        FileInputStream fis = new FileInputStream( kbaseFile );
        KieSession knowledgeSession = loadSession( fis );

        ArrayList list = new ArrayList();
        knowledgeSession.setGlobal( "list", list );

        knowledgeSession.insert( 30 );
        knowledgeSession.fireAllRules();

        assertEquals( 1, list.size() );
        assertEquals( "Tick", list.get( 0 ).getClass().getSimpleName() );

    } catch ( Exception e ) {
        e.printStackTrace();
        fail( e.getMessage() );
    }

}
 
Example 3
Source File: OOPathMultilevelTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassTwoLevelPath() {
    final String drl =
            "import org.drools.compiler.oopath.model.*;\n" +
                    "global java.util.List list\n" +
                    "\n" +
                    "rule R when\n" +
                    "  Man( $toy: /wife/children/toys )\n" +
                    "then\n" +
                    "  list.add( $toy.getName() );\n" +
                    "end\n";

    final KieSession ksession = new KieHelper().addContent( drl, ResourceType.DRL )
            .build()
            .newKieSession();

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

    final Woman alice = new Woman( "Alice", 38 );
    final Man bob = new Man( "Bob", 40 );
    bob.setWife( alice );

    final Child charlie = new Child( "Charles", 12 );
    final Child debbie = new Child( "Debbie", 8 );
    alice.addChild( charlie );
    alice.addChild( debbie );

    charlie.addToy( new Toy( "car" ) );
    charlie.addToy( new Toy( "ball" ) );
    debbie.addToy( new Toy( "doll" ) );

    ksession.insert( bob );
    ksession.fireAllRules();

    assertThat(list).containsExactlyInAnyOrder("car", "ball", "doll");
}
 
Example 4
Source File: PropertyReactivityTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropReactiveUpdate() {
    // DROOLS-1275
    final String str1 =
            "import " + Klass.class.getCanonicalName() + "\n" +
            "global java.util.List list;\n" +
            "rule R when\n" +
            "  Klass( b == 2 )\n" +
            "then\n" +
            "  list.add(\"fired\");\n" +
            "end\n";

    final KieSession ksession = new KieHelper().addContent( str1, ResourceType.DRL )
                                         .build()
                                         .newKieSession();

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

    final Klass bean = new Klass( 1, 2, 3, 4, 5, 6 );
    final FactHandle fh = ksession.insert( bean );
    ksession.fireAllRules();
    assertEquals( 1, list.size() );

    ( (StatefulKnowledgeSessionImpl) ksession ).update( fh, bean, "a", "d" );
    ksession.fireAllRules();
    assertEquals( 1, list.size() );

    ( (StatefulKnowledgeSessionImpl) ksession ).update( fh, bean, "c", "b" );
    ksession.fireAllRules();
    assertEquals( 2, list.size() );
}
 
Example 5
Source File: NamedConsequencesTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamedConsequenceAfterNotPattern() {
    // DROOLS-5
    String str = "import org.drools.compiler.Cheese;\n " +
            "global java.util.List results;\n" +
            "\n" +
            "rule R1 when\n" +
            "    $a: Cheese ( type == \"stilton\" )\n" +
            "    not Cheese ( type == \"brie\" )\n" +
            "    do[t1]\n" +
            "    $b: Cheese ( type == \"cheddar\" )\n" +
            "then\n" +
            "    results.add( $b.getType() );\n" +
            "then[t1]\n" +
            "    results.add( $a.getType() );\n" +
            "end\n";

    KieBase kbase = loadKnowledgeBaseFromString(str);
    KieSession ksession = kbase.newKieSession();

    List<String> results = new ArrayList<String>();
    ksession.setGlobal( "results", results );

    ksession.insert( new Cheese( "stilton", 5 ) );
    ksession.insert( new Cheese("cheddar", 7 ) );

    ksession.fireAllRules();

    assertTrue(results.contains("stilton"));
    assertTrue(results.contains("cheddar"));
}
 
Example 6
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 7
Source File: PropertyReactivityTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyChangeSupportNewAPI() throws Exception {
    final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_PropertyChangeTypeDecl.drl"));
    final KieSession session = createKnowledgeSession(kbase);

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

    final State state = new State("initial");
    session.insert(state);
    session.fireAllRules();

    assertEquals(1, ((List) session.getGlobal("list")).size());

    state.setFlag(true);
    assertEquals(1, ((List) session.getGlobal("list")).size());

    session.fireAllRules();
    assertEquals(2, ((List) session.getGlobal("list")).size());

    state.setState("finished");

    session.dispose();

    // checks that the session removed itself from the bean listeners list
    assertEquals(0, state.getPropertyChangeListeners().length);
}
 
Example 8
Source File: PropertyReactivityBlockerTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test()
public void testA_Working() {
    // DROOLS-644
    String drl =
            "import " + Person.class.getCanonicalName() + ";\n" +
            "global java.util.List list;\n" +
            "rule R when\n" +
            "    $p1 : Person( name == \"Mario\", $a1: age ) \n" +
            "    $p2 : Person( age > $a1 ) \n" +
            "then\n" +
            "    list.add(\"t0\");\n" +
            "end\n";

    KieSession ksession = new KieHelper().addContent(drl, ResourceType.DRL)
            .build()
            .newKieSession();
    
    ReteDumper.dumpRete(ksession);

    List<String> list = new ArrayList<String>();
    ksession.setGlobal("list", list);

    Person mario = new Person("Mario", 40);
    Person mark = new Person("Mark", 37);
    FactHandle fh_mario = ksession.insert(mario);
    ksession.insert(mark);
    ksession.fireAllRules();
    
    mario.setAge(35);
    ksession.update(fh_mario, mario, "age");
    
    int x = ksession.fireAllRules();
    assertEquals(1, list.size());
    assertEquals("t0", list.get(0));
}
 
Example 9
Source File: SerializedPackageMergeTwoSteps2Test.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test @Disabled
public void testBuildAndSerializePackagesInTwoSteps2() throws IOException, ClassNotFoundException    {        

    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    // Read the two serialized knowledgePackages
    for(String fileName : SerializedPackageMergeTwoSteps1Test.BINPKG) {
        Collection<KiePackage> kpkgs=null;
        byte[] data=null;
        try {
        	data=Files.readAllBytes(Paths.get(fileName));
        } catch(java.nio.file.NoSuchFileException ex) {
            // bin file does not exist, finish test
            return;
        }
    	kpkgs=_deserializeFromBytes(data);  
    	if(kpkgs!=null)
    		kbase.addPackages(kpkgs); 
    }    

    Collection<KiePackage> knowledgePackagesCombined = kbase.getKiePackages();

    // serialize
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream out = new DroolsObjectOutputStream( baos );
    out.writeObject( knowledgePackagesCombined );
    out.flush();
    out.close();

    // deserialize
    ObjectInputStream in = new DroolsObjectInputStream( new ByteArrayInputStream( baos.toByteArray() ) );
    Collection<KiePackage> deserializedPackages = (Collection<KiePackage>) in.readObject();

    // Use the deserialized knowledgePackages
    InternalKnowledgeBase kbase2 = KnowledgeBaseFactory.newKnowledgeBase();
    kbase2.addPackages(deserializedPackages);

    KieSession ksession = kbase2.newKieSession();
    try {
        List<String> list = new ArrayList<String>();
        ksession.setGlobal( "list", list );
        ksession.insert(new org.drools.compiler.Person("John"));
        ksession.fireAllRules();

        assertEquals(2, list.size());
    } finally {
        ksession.dispose();
    }
}
 
Example 10
Source File: UnlinkingTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void multipleJoinsUsingSameOTN() throws Exception {
    KieBase kbase = loadKnowledgeBase("test_LRUnlinking.drl");
    kbase = SerializationHelper.serializeObject( kbase );

    final KieSession wmOne = kbase.newKieSession();
    final KieSession wmTwo = kbase.newKieSession();

    final List<Person> listOne = new ArrayList<Person>();
    final List<Person> listTwo = new ArrayList<Person>();

    wmOne.setGlobal( "results",
                     listOne );
    wmTwo.setGlobal( "results",
                     listTwo );

    Person name = new Person();
    Person likes = new Person();
    Person age = new Person();
    Person hair = new Person();
    Person happy = new Person();
    Person match = new Person();

    name.setName( "Ana" );
    likes.setLikes( "Chocolate" );
    age.setAge( 30 );
    hair.setHair( "brown" );
    happy.setHappy( true );

    match.setName( "Leo" );
    match.setLikes( "Chocolate" );
    match.setAge( 30 );
    match.setHair( "brown" );
    match.setHappy( true );
    
    // WM One - first round of inserts
    wmOne.insert( name );
    wmOne.insert( likes );
    wmOne.insert( age );

    wmOne.fireAllRules();

    assertEquals( 0,
                  listOne.size(),
                  "Should not have fired");

    // WM Two - first round o inserts
    wmTwo.insert( name );
    wmTwo.insert( likes );
    wmTwo.insert( age );

    wmTwo.fireAllRules();

    assertEquals( 0,
                  listTwo.size(),
                  "Should not have fired");
    
    wmOne.insert( hair );
    wmOne.insert( happy );
    InternalFactHandle matchHandle = (InternalFactHandle) wmOne.insert( match );
    
    wmOne.fireAllRules();
    
    assertTrue(listOne.size() > 0,  "Should have fired");
            
    assertEquals(matchHandle.getObject(),
                 listOne.get( 0 ),
                 "Should have inserted the match Person");
    
    wmTwo.fireAllRules();
    
    assertEquals(0,
                 listTwo.size(),
                 "Should not have fired");
    
    wmTwo.insert( hair );
    wmTwo.insert( happy );
    wmTwo.insert( match );
    
    wmTwo.fireAllRules();

    assertTrue(listTwo.size() > 0,
               "Should have fired");

}
 
Example 11
Source File: QueryTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testQueryWithExpressionAsArgument() throws Exception {
    // DROOLS-414
    String str =
            "import org.drools.compiler.Person\n" +
            "global java.util.List persons;\n" +
            "\n" +
            "query checkLength(String $s, int $l)\n" +
            "    $s := String( length == $l )\n" +
            "end\n" +
            "\n" +
            "rule R when\n" +
            "    $i : Integer()\n" +
            "    $p : Person()\n" +
            "    checkLength( $p.name, 1 + $i + $p.age; )\n" +
            "then\n" +
            "    persons.add( $p );\n" +
            "end\n";

    KieHelper helper = new KieHelper();
    helper.addContent( str, ResourceType.DRL );
    KieBase kbase = SerializationHelper.serializeObject(helper.build());
    KieSession ksession = kbase.newKieSession();

    List<Person> list = new ArrayList<Person>();
    ksession.setGlobal("persons", list);

    ksession.insert(1);
    ksession.insert("Mark");
    ksession.insert("Edson");
    ksession.insert("Mario");
    ksession.insert(new Person("Mark", 2));
    ksession.insert(new Person("Edson", 3));
    ksession.insert(new Person("Mario", 4));
    ksession.fireAllRules();

    System.out.println(list);
    assertEquals(2, list.size());
    for (Person p : list) {
        assertTrue( p.getName().equals( "Mark" ) || p.getName().equals( "Edson" ) );
    }
}
 
Example 12
Source File: TraitFieldsAndLegacyClassesTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@ParameterizedTraitFieldsAndLegacyClassesTest
public void testTraitFieldUpdate0(VirtualPropertyMode mode) {

    String drl = "" +
            "package org.drools.factmodel.traits0;\n" +
            "\n" +
            "import org.drools.core.factmodel.traits.Traitable;\n" +
            "import org.drools.core.factmodel.traits.Thing;\n" +
            "import java.util.*\n" +
            "import org.drools.compiler.factmodel.traits.TraitFieldsAndLegacyClassesTest.Parent;\n" +
            "import org.drools.compiler.factmodel.traits.TraitFieldsAndLegacyClassesTest.Child;\n" +
            "global java.util.List list;\n" +
            "\n" +
            "declare trait ParentTrait\n" +
            "@propertyReactive\n" +
            "    child : Child\n" +
            "    age : int = 24\n" +
            "end\n" +

            "declare Parent\n" +
            "@Traitable\n" +
            "@propertyReactive\n" +
            "end\n" +

            "rule \"Init\" \n" +
            "\n" +
            "when\n" +
            "    \n" +
            "then\n" +
            "   Parent p = new Parent(\"parent\", null);\n" +
            "   Map map = new HashMap();\n" +
            "   map.put( \"parent\", ParentTrait.class );\n" +
            "   insert(p);\n" +
            "   insert(map);\n" +
            "end\n" +
            "\n" +

            "rule \"trait parent\" \n" +
            "\n" +
            "when\n" +
            "   $p : Parent( name == \"parent\" )\n" +
            "   $map : HashMap([parent] != null)\n" +
            "then\n" +
            "   Object p = don ( $p , (Class) $map.get(\"parent\") );\n" +
            "   list.add(\"correct\");\n" +
            "end\n" +
            "\n" +
            "\n";

    KieBase kBase = loadKnowledgeBaseFromString(drl);
    TraitFactory.setMode(mode, kBase);

    KieSession knowledgeSession = kBase.newKieSession();
    List list = new ArrayList();
    knowledgeSession.setGlobal("list", list);

    knowledgeSession.fireAllRules();
    assertTrue(list.contains("correct"));
    assertEquals(1, list.size());
}
 
Example 13
Source File: TruthMaintenanceTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testLogicalThenStatedShadowSingleOccurance() {
    String droolsSource =
            "package org.drools.tms.test; \n" +

            "global java.util.List list; \n" +

            "rule Justify \n" +
            "when \n" +
            "    String( this == 'go1' ) " +
            "then \n" +
            "    insertLogical( 'f1' ); \n" +
            "end \n" +


            "rule StillHere \n" +
            "when \n" +
            "    String( this == 'go2' ) " +
            "    s : String( this == 'f1' ) " +
            "then \n" +
            "    list.add( s ); \n" +
            "end \n" +
            ""
            ;

    KieBaseConfiguration kieConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kieConf.setOption( EqualityBehaviorOption.IDENTITY );
    KieBase kbase = loadKnowledgeBaseFromString( kieConf, droolsSource );
    KieSession session = kbase.newKieSession();
    try {
        List list = new ArrayList();
        session.setGlobal("list", list);

        session.insert( "go1" );
        session.fireAllRules();

        TruthMaintenanceSystem tms = ((StatefulKnowledgeSessionImpl)session).getTruthMaintenanceSystem();
        InternalFactHandle jfh1 = tms.get( "f1" ).getLogicalFactHandle();
        assertEquals(EqualityKey.JUSTIFIED, jfh1.getEqualityKey().getStatus());

        InternalFactHandle fh1 = (InternalFactHandle) session.insert( "f1" );
        InternalFactHandle fh2 = (InternalFactHandle) session.insert( "f2" );

        session.insert("go2");
        session.fireAllRules();

        assertEquals(EqualityKey.STATED, fh1.getEqualityKey().getStatus());
        assertSame( fh1.getEqualityKey(), jfh1.getEqualityKey() );
        assertNotSame( fh1, jfh1 );

        EqualityKey key = jfh1.getEqualityKey();
        assertSame( fh1.getEqualityKey(), key );
        assertNotSame( fh1, jfh1 );

        assertEquals(2, key.size());
        assertSame( jfh1,  key.getLogicalFactHandle() );

        // Make sure f1 only occurs once
        assertEquals(1, list.size());
        assertEquals("f1", list.get(0 ));
    } finally {
        session.dispose();
    }
}
 
Example 14
Source File: DynamicRulesTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testDynamicRuleRemovalsSubNetwork() throws Exception {
    Collection<KiePackage> kpkgs = SerializationHelper.serializeObject( loadKnowledgePackages( "test_DynamicRulesWithSubnetwork1.drl",
                                                                                                     "test_DynamicRulesWithSubnetwork.drl" ) );
    
    InternalKnowledgeBase kbase = (InternalKnowledgeBase) loadKnowledgeBase();
    kbase.addPackages( kpkgs );
    
    kpkgs = SerializationHelper.serializeObject( loadKnowledgePackages( "test_DynamicRulesWithSubnetwork2.drl" ) );
    kbase.addPackages( kpkgs );

    KieSession session = createKnowledgeSession( kbase );

    final List<?> list = new ArrayList<Object>();
    session.setGlobal( "results",
                       list );

    Order order = new Order();

    OrderItem item1 = new OrderItem( order,
                                     1,
                                     "Adventure Guide Brazil",
                                     OrderItem.TYPE_BOOK,
                                     24 );
    order.addItem( item1 );
    FactHandle item1Fh = session.insert( item1 );

    OrderItem item2 = new OrderItem( order,
                                     2,
                                     "Prehistoric Britain",
                                     OrderItem.TYPE_BOOK,
                                     15 );
    order.addItem( item2 );
    FactHandle item2Fh = session.insert( item2 );

    OrderItem item3 = new OrderItem( order,
                                     3,
                                     "Holiday Music",
                                     OrderItem.TYPE_CD,
                                     9 );
    order.addItem( item3 );
    FactHandle item3Fh = session.insert( item3 );

    OrderItem item4 = new OrderItem( order,
                                     4,
                                     "Very Best of Mick Jagger",
                                     OrderItem.TYPE_CD,
                                     11 );
    order.addItem( item4 );
    FactHandle item4Fh = session.insert( item4 );

    session.insert( order );
    session.fireAllRules();
    assertEquals( 11, list.size() );

    kbase.removeRule( "org.drools.compiler",
                      "Apply Discount on all books" );

    list.clear();
    session.update( item1Fh, item1 );
    session.update( item2Fh, item2 );
    session.update( item3Fh, item3 );
    session.update( item4Fh, item4 );
    session.fireAllRules();

    assertEquals( 10, list.size() );

    kbase.removeRule( "org.drools.compiler",
                      "like book" );
    list.clear();
    session.update( item1Fh, item1 );
    session.update( item2Fh, item2 );
    session.update( item3Fh, item3 );
    session.update( item4Fh, item4 );
    session.fireAllRules();

    assertEquals( 8, list.size() );

    final OrderItem item5 = new OrderItem( order, 5, "Sinatra : Vegas", OrderItem.TYPE_CD, 5 );
    FactHandle item5Fh = session.insert( item5 );

    session.fireAllRules();

    assertEquals( 10, list.size() );

    kbase.removeKiePackage( "org.drools.compiler" );
    list.clear();
    session.update( item1Fh, item1 );
    session.update( item2Fh, item2 );
    session.update( item3Fh, item3 );
    session.update( item4Fh, item4 );
    session.update( item5Fh, item5 );
    session.fireAllRules();

    assertEquals( 0, list.size() );
}
 
Example 15
Source File: KnowledgeBuilderTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testDifferentPackages() throws Exception {
    String rule = "package org.drools.compiler.test.rule\n" +
                  "import org.drools.compiler.testA.FactA\n" +
                  "import org.drools.compiler.testB.FactB\n" +
                  "rule R1 when\n" +
                  "   $fieldA : FactA( $fieldB : fieldB, bigint == 1 )\n" +
                  "   FactB( this == $fieldB, fieldA == $fieldA )\n" +
                  "then\n" +
                  "   list.add(\"OK\");" +
                  "end";

    String declarationA = "package org.drools.compiler.testA\n" +
                          "import org.drools.compiler.testB.FactB\n" +
                          "import java.math.BigInteger\n" +
                          "declare FactA\n" +
                          "    fieldB: FactB\n" +
                          "    bigint: BigInteger\n" +
                          "end\n";

    String declarationB = "package org.drools.compiler.testB\n" +
                          "import org.drools.compiler.testA.FactA\n" +
                          "global java.util.List list\n" +
                          "declare FactB\n" +
                          "    fieldA: FactA\n" +
                          "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.batch()
            .type( ResourceType.DRL )
            .add( ResourceFactory.newByteArrayResource( rule.getBytes() ) )
            .add( ResourceFactory.newByteArrayResource( declarationA.getBytes() ) )
            .add( ResourceFactory.newByteArrayResource( declarationB.getBytes() ) )
            .build();


    if ( kbuilder.hasErrors() ) {
        fail( kbuilder.getErrors().toString() );
    }

    String declarationC = "package org.drools.compiler.testA\n" +
                          "declare FactC\n" +
                          "    field : UnknownClass\n" +
                          "end\n";

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

    assertTrue( kbuilder.hasErrors() );
    kbuilder.undo();
    assertFalse( kbuilder.hasErrors() );

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

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

    FactType aType = kbase.getFactType( "org.drools.compiler.testA", "FactA" );
    Object a = aType.newInstance();
    FactType bType = kbase.getFactType( "org.drools.compiler.testB", "FactB" );
    Object b = bType.newInstance();
    aType.set( a, "fieldB", b );
    aType.set( a, "bigint", new BigInteger( "1" ) );
    bType.set( b, "fieldA", a );
    ksession.insert( a );
    ksession.insert( b );

    int rules = ksession.fireAllRules();
    assertEquals( 1, rules );
    assertEquals( "OK", list.get( 0 ) );
}
 
Example 16
Source File: ProcessSplitTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testSplitWithJavaContextConstraint() {
    Reader source = new StringReader(
        "<process xmlns=\"http://drools.org/drools-5.0/process\"" +
        "         xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"" +
        "         xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"" +
        "         type=\"RuleFlow\" name=\"ruleflow\" id=\"org.jbpm.process-split\" package-name=\"org.jbpm\" >" +
        "" +
        "  <header>" +
        "    <imports>" +
        "      <import name=\"org.jbpm.integrationtests.test.Person\" />" +
        "      <import name=\"org.jbpm.integrationtests.ProcessSplitTest.ProcessUtils\" />" +
        "    </imports>" +
        "    <globals>" +
        "      <global identifier=\"list\" type=\"java.util.List\" />" +
        "    </globals>" +
        "    <variables>\n" +
        "      <variable name=\"name\" >\n" +
        "        <type name=\"org.jbpm.process.core.datatype.impl.type.StringDataType\" />\n" +
        "      </variable>\n" +
        "    </variables>\n" +
        "  </header>" +
        "" +
        "  <nodes>" +
        "    <actionNode id=\"2\" name=\"Action\" >" +
        "        <action type=\"expression\" dialect=\"mvel\" >insert(context.getProcessInstance());</action>" +
        "    </actionNode>" +
        "    <split id=\"4\" name=\"Split\" type=\"2\" >" +
        "      <constraints>" +
        "        <constraint toNodeId=\"8\" toType=\"DROOLS_DEFAULT\" priority=\"2\" type=\"code\" dialect=\"java\" >return true;</constraint>" +
        "        <constraint toNodeId=\"6\" toType=\"DROOLS_DEFAULT\" priority=\"1\" type=\"code\" dialect=\"java\" >return context.getVariable(\"name\") != null &amp;&amp; ((String) context.getVariable(\"name\")).length() > 0;</constraint>" +
        "      </constraints>" +
        "    </split>" +
        "    <end id=\"8\" name=\"End\" />" +
        "    <actionNode id=\"6\" name=\"Action\" >" +
        "        <action type=\"expression\" dialect=\"mvel\" >list.add(context.getProcessInstance().getId());</action>" +
        "    </actionNode>" +
        "    <start id=\"1\" name=\"Start\" />" +
        "    <end id=\"3\" name=\"End\" />" +
        "  </nodes>" +
        "  <connections>" +
        "    <connection from=\"1\" to=\"2\" />" +
        "    <connection from=\"2\" to=\"4\" />" +
        "    <connection from=\"4\" to=\"8\" />" +
        "    <connection from=\"4\" to=\"6\" />" +
        "    <connection from=\"6\" to=\"3\" />" +
        "  </connections>" +
        "" +
        "</process>");
    builder.addRuleFlow(source);

    KieSession workingMemory = createKieSession(builder.getPackages());
    
    List<Long> list = new ArrayList<Long>();
    workingMemory.setGlobal("list", list);

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("name", "John Doe");
    ProcessInstance processInstance = ( ProcessInstance )
        workingMemory.startProcess("org.jbpm.process-split", params);
    
    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
    assertEquals(1, list.size());
}
 
Example 17
Source File: TraitMapCoreTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testDrools217(){

    String drl = "" +
            "\n" +
            "package org.drools.core.factmodel.traits.test;\n" +
            "\n" +
            "import java.util.*;\n" +
            "import org.drools.core.factmodel.traits.Alias\n" +
            "\n" +
            "global java.util.List list;\n" +
            "" +
            "declare HashMap @Traitable(logical=true) end \n" +
            "\n" +
            "declare trait Citizen\n" +
            "@traitable\n" +
            "    citizenship : String = \"Unknown\"\n" +
            "end\n" +
            "\n" +
            "declare trait Student extends Citizen\n" +
            "@propertyReactive\n" +
            "   ID : String = \"412314\" @Alias(\"personID\")\n" +
            "   GPA : Double = 3.99\n" +
            "end\n" +
            "\n" +
            "declare Person\n" +
            "@Traitable\n" +
            "    personID : String\n" +
            "    isStudent : boolean\n" +
            "end\n" +
            "\n" +
            "declare trait Worker\n" +
            "@propertyReactive\n" +
            "    hasBenefits : Boolean = true\n" +
            "end\n" +
            "\n" +
            "\n" +
            "rule \"1\"\n" +
            "salience 1\n" +
            "no-loop\n" +
            "when\n" +
            "then\n" +
            "    Person p = new Person(\"1020\",true);\n" +
            "    Map map = new HashMap();\n" +
            "    map.put(\"isEmpty\",true);\n" +
            "    insert(p);\n" +
            "    insert(map);\n" +
            "    list.add(\"initialized\");\n" +
            "end\n" +
            "\n" +
            "rule \"2\"\n" +
            "salience 1\n" +
            "no-loop\n" +
            "when\n" +
            "    $stu : Person(isStudent == true)\n" +
            "    $map : Map(this[\"isEmpty\"] == true)\n" +
            "then\n" +
            "    Student s = don( $stu , Student.class );\n" +
            "    $map.put(\"worker\" , s);\n" +
            "    $map.put(\"isEmpty\" , false);\n" +
            "    update($map);\n" +
            "    System.out.println(\"don: Person -> Student \");\n" +
            "    list.add(\"student is donned\");\n" +
            "end\n" +
            "\n" +
            "rule \"3\"\n" +
            "salience 1\n" +
            "no-loop\n" +
            "when\n" +
            "    $map : Map($stu : this[\"worker\"], $stu isA Student.class)\n" +
            "then\n" +
            "    Object obj = don( $map , Worker.class );\n" +
            "    System.out.println(\"don: Map -> Worker : \"+obj);\n" +
            "    list.add(\"worker is donned\");\n" +
            "end\n";

    KieSession ksession = loadKnowledgeBaseFromString(drl).newKieSession();

    TraitFactory.setMode(VirtualPropertyMode.MAP, ksession.getKieBase());
    List list = new ArrayList();
    ksession.setGlobal("list", list);
    ksession.fireAllRules();

    assertTrue(list.contains("initialized"));
    assertTrue(list.contains("student is donned"));
    assertTrue(list.contains("worker is donned"));
}
 
Example 18
Source File: ProcessStateTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
 public void testDelayedStateConstraint() {
 	KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
     Reader source = new StringReader(
         "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
         "<process xmlns=\"http://drools.org/drools-5.0/process\"\n" +
         "         xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
         "         xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n" +
         "         type=\"RuleFlow\" name=\"flow\" id=\"org.drools.state\" package-name=\"org.jbpm\" version=\"1\" >\n" +
         "\n" +
         "  <header>\n" +
"    <imports>\n" +
"      <import name=\"org.jbpm.integrationtests.test.Person\" />\n" +
"    </imports>\n" +
"    <globals>\n" +
"      <global identifier=\"list\" type=\"java.util.List\" />\n" +
"    </globals>\n" +
         "  </header>\n" +
         "\n" +
         "  <nodes>\n" +
         "    <start id=\"1\" name=\"Start\" />\n" +
         "    <state id=\"2\" >\n" +
         "      <constraints>\n" +
         "        <constraint toNodeId=\"3\" name=\"one\" >\n" +
         "            Person( age &gt; 21 )" +
         "        </constraint>"+
          "       <constraint toNodeId=\"4\" name=\"two\" >\n" +
         "           Person( age &lt;= 21 )" +
         "        </constraint>"+
         "      </constraints>\n" +
         "    </state>\n" +
"    <actionNode id=\"3\" name=\"ActionNode1\" >\n" +
"      <action type=\"expression\" dialect=\"java\" >list.add(\"1\");</action>\n" +
"    </actionNode>\n" +
         "    <end id=\"4\" name=\"End\" />\n" +
"    <actionNode id=\"5\" name=\"ActionNode2\" >\n" +
"      <action type=\"expression\" dialect=\"java\" >list.add(\"2\");</action>\n" +
"    </actionNode>\n" +
         "    <end id=\"6\" name=\"End\" />\n" +
         "  </nodes>\n" +
         "\n" +
         "  <connections>\n" +
         "    <connection from=\"1\" to=\"2\" />\n" +
         "    <connection from=\"2\" to=\"3\" />\n" +
         "    <connection from=\"3\" to=\"4\" />\n" +
         "    <connection from=\"2\" to=\"5\" />\n" +
         "    <connection from=\"5\" to=\"6\" />\n" +
         "  </connections>\n" +
         "\n" +
         "</process>");
     kbuilder.add( ResourceFactory.newReaderResource( source ), ResourceType.DRF );
     KieBase kbase = kbuilder.newKieBase();
     KieSession ksession = kbase.newKieSession();
     List<String> list = new ArrayList<String>();
     ksession.setGlobal("list", list);
     ProcessInstance processInstance = ksession.startProcess("org.drools.state");
     assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
     assertTrue(list.isEmpty());
     Person person = new Person("John Doe", 30);
     ksession.insert(person);
     ksession.fireAllRules();
     assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
     assertEquals(1, list.size());
     assertEquals("1", list.get(0));
 }
 
Example 19
Source File: AbductionTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testAbductiveLogicWithConstructorArgs() {
    String droolsSource =
            "package org.drools.abductive.test; \n" +
            "" +
            "import " + Abducible.class.getName() + "; \n" +
            "global java.util.List list; \n" +
            "" +
            "declare Foo \n" +
            "   @Abducible \n" +
            "   id : Integer @key \n" +
            "   name : String @key \n" +
            "   value : double \n" +
            "   flag : boolean \n" +
            "end \n" +

            "query foo() \n" +
            "   @Abductive( target=Foo.class ) \n" +
            "end \n" +

            "query foo2( Integer $i, String $name ) \n" +
            "   @Abductive( target=Foo.class ) \n" +
            "   $i := Integer() from new Integer( 4 ) \n" +
            "   $name := String() " +
            "end \n" +

            "query foo3( Integer $i, String $name, double $val, boolean $bool ) \n" +
            "   @Abductive( target=Foo.class ) \n" +
            "end \n" +

            "rule Init " +
            "   salience 9999 " +
            "when " +
            "then " +
            "   System.out.println( 'Foo zero is in' ); \n" +
            "   insert( new Foo() ); \n" +
            "end " +

            "rule R1 " +
            "when " +
            "   $fx : foo() " +
            "then " +
            "   list.add( 1 ); " +
            "end \n" +
            "" +
            "rule R2 " +
            "when " +
            "   foo2( 4, $n ; ) " +
            "then " +
            "   list.add( 2 ); " +
            "end \n" +
            "" +
            "rule R3 " +
            "when " +
            "   foo3( 42, \"test2\", $dbl, $bool ; ) " +
            "then " +
            "   list.add( 3 ); " +
            "end \n" +
            "" +
            "";
    /////////////////////////////////////

    KieSession session = getSessionFromString( droolsSource );
    List list = new ArrayList();
    session.setGlobal( "list", list );

    session.insert( "john" );

    session.fireAllRules();

    for ( Object o : session.getObjects() ) {
        System.out.println( ">> " + o );
    }
    System.err.println( list );
    assertEquals( Arrays.asList( 1, 2, 3 ), list );
}
 
Example 20
Source File: ProcessFlowControlTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testRuleFlowConstraintDialects() throws Exception {
    builder.addRuleFlow( new InputStreamReader( getClass().getResourceAsStream( "test_ConstraintDialects.rfm" ) ) );

    logger.error( builder.getErrors().toString() );

    assertEquals( 0,
                  builder.getErrors().getErrors().length );

    KieSession session = createKieSession(true, builder.getPackages());
    List<Integer> inList = new ArrayList<Integer>();
    List<Integer> outList = new ArrayList<Integer>();
    session.setGlobal( "inList",
                       inList );
    session.setGlobal( "outList",
                       outList );

    inList.add( 1 );
    inList.add( 3 );
    inList.add( 6 );
    inList.add( 25 );

    FactHandle handle = session.insert( inList );
    session.startProcess( "ConstraintDialects" );
    assertEquals( 4,
                  outList.size() );
    assertEquals( "MVELCodeConstraint was here",
                  outList.get( 0 ) );
    assertEquals( "JavaCodeConstraint was here",
                  outList.get( 1 ) );
    assertEquals( "MVELRuleConstraint was here",
                  outList.get( 2 ) );
    assertEquals( "JavaRuleConstraint was here",
                  outList.get( 3 ) );

    outList.clear();
    inList.remove( new Integer( 1 ) );
    session.update( handle,
                    inList );
    session.startProcess( "ConstraintDialects" );
    assertEquals( 3,
                  outList.size() );
    assertEquals( "JavaCodeConstraint was here",
                  outList.get( 0 ) );
    assertEquals( "MVELRuleConstraint was here",
                  outList.get( 1 ) );
    assertEquals( "JavaRuleConstraint was here",
                  outList.get( 2 ) );

    outList.clear();
    inList.remove( new Integer( 6 ) );
    session.update( handle,
                    inList );
    session.startProcess( "ConstraintDialects" );
    assertEquals( 2,
                  outList.size() );
    assertEquals( "JavaCodeConstraint was here",
                  outList.get( 0 ) );
    assertEquals( "JavaRuleConstraint was here",
                  outList.get( 1 ) );

    outList.clear();
    inList.remove( new Integer( 3 ) );
    session.update( handle,
                    inList );
    session.startProcess( "ConstraintDialects" );
    assertEquals( 1,
                  outList.size() );
    assertEquals( "JavaRuleConstraint was here",
                  outList.get( 0 ) );

    outList.clear();
    inList.remove( new Integer( 25 ) );
    session.update( handle,
                    inList );
    ProcessInstance processInstance = session.startProcess( "ConstraintDialects" );
    
    assertEquals( ProcessInstance.STATE_ERROR,
                  processInstance.getState() );
}