Search in sources :

Example 66 with DefaultFactHandle

use of org.drools.core.common.DefaultFactHandle in project drools by kiegroup.

the class NodeSegmentUnlinkingTest method testAllLinkedInWithNotNodesOnly.

@Test
public void testAllLinkedInWithNotNodesOnly() {
    setUp(NOT_NODE);
    // make sure it created NotNodes
    assertEquals(NotNode.class, n3.getClass());
    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(kconf);
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
    BetaMemory bm = (BetaMemory) ksession.getNodeMemory(n3);
    createSegmentMemory(n3, ksession);
    // not nodes start off linked
    assertTrue(bm.getSegmentMemory().isSegmentLinked());
    // unlinked after first assertion
    DefaultFactHandle f1 = (DefaultFactHandle) ksession.insert("test1");
    n3.assertObject(f1, context, ksession);
    // this doesn't unlink on the assertObject, as the node's memory must be processed. So use the helper method the main network evaluator uses.
    PhreakNotNode.unlinkNotNodeOnRightInsert((NotNode) n3, bm, ksession);
    assertFalse(bm.getSegmentMemory().isSegmentLinked());
    n3.retractRightTuple(f1.getFirstRightTuple(), context, ksession);
    assertTrue(bm.getSegmentMemory().isSegmentLinked());
// assertFalse( bm.getSegmentMemory().isSigmentLinked() ); // check retraction unlinks again
}
Also used : KieBaseConfiguration(org.kie.api.KieBaseConfiguration) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 67 with DefaultFactHandle

use of org.drools.core.common.DefaultFactHandle in project drools by kiegroup.

the class ReteTest method testAssertObject.

/**
 * Test asserts correctly propagate
 *
 * @throws Exception
 */
@Test
public void testAssertObject() throws Exception {
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
    // Create a Rete network with ObjectTypeNodes for List, Collection and ArrayList
    final Rete rete = kBase.getRete();
    final ObjectTypeNode objectTypeNode = new ObjectTypeNode(1, this.entryPoint, new ClassObjectType(List.class), buildContext);
    objectTypeNode.attach(buildContext);
    final MockObjectSink sink1 = new MockObjectSink();
    objectTypeNode.addObjectSink(sink1);
    // There are no String ObjectTypeNodes, make sure its not propagated
    final String string = "String";
    final DefaultFactHandle h1 = new DefaultFactHandle(1, string);
    rete.assertObject(h1, pctxFactory.createPropagationContext(0, PropagationContext.Type.INSERTION, null, null, null), ksession);
    assertLength(0, sink1.getAsserted());
    // There is a List ObjectTypeNode, make sure it was propagated
    final List list = new ArrayList();
    final DefaultFactHandle h2 = new DefaultFactHandle(1, list);
    rete.assertObject(h2, pctxFactory.createPropagationContext(0, PropagationContext.Type.INSERTION, null, null, null), ksession);
    ksession.fireAllRules();
    final List asserted = sink1.getAsserted();
    assertLength(1, asserted);
    final Object[] results = (Object[]) asserted.get(0);
    assertSame(list, ((DefaultFactHandle) results[0]).getObject());
}
Also used : DefaultFactHandle(org.drools.core.common.DefaultFactHandle) ClassObjectType(org.drools.core.base.ClassObjectType) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Example 68 with DefaultFactHandle

use of org.drools.core.common.DefaultFactHandle in project drools by kiegroup.

the class RuleUnlinkingWithSegmentMemoryTest method testRuleSegmentLinking.

@Test
public void testRuleSegmentLinking() {
    setUp(JOIN_NODE);
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl wm = new StatefulKnowledgeSessionImpl(1L, kBase);
    BetaMemory bm = null;
    List<PathMemory> list;
    PathMemory rtn1Rs = (PathMemory) wm.getNodeMemory(rtn1);
    PathMemory rtn2Rs = (PathMemory) wm.getNodeMemory(rtn2);
    PathMemory rtn3Rs = (PathMemory) wm.getNodeMemory(rtn3);
    DefaultFactHandle f1 = (DefaultFactHandle) wm.insert("test1");
    lian.assertObject(f1, context, wm);
    n1.assertObject(f1, context, wm);
    n3.assertObject(f1, context, wm);
    n4.assertObject(f1, context, wm);
    n8.assertObject(f1, context, wm);
    assertFalse(rtn1Rs.isRuleLinked());
    assertFalse(rtn2Rs.isRuleLinked());
    assertFalse(rtn3Rs.isRuleLinked());
    // Link in Rule1
    bm = (BetaMemory) wm.getNodeMemory(n2);
    assertFalse(bm.getSegmentMemory().isSegmentLinked());
    DefaultFactHandle f2 = (DefaultFactHandle) wm.insert("test2");
    n2.assertObject(f2, context, wm);
    assertTrue(bm.getSegmentMemory().isSegmentLinked());
    assertTrue(rtn1Rs.isRuleLinked());
    assertFalse(rtn2Rs.isRuleLinked());
    assertFalse(rtn3Rs.isRuleLinked());
    // Link in Rule2
    bm = (BetaMemory) wm.getNodeMemory(n5);
    assertFalse(bm.getSegmentMemory().isSegmentLinked());
    n5.assertObject(f1, context, wm);
    assertTrue(bm.getSegmentMemory().isSegmentLinked());
    assertTrue(rtn1Rs.isRuleLinked());
    assertTrue(rtn2Rs.isRuleLinked());
    assertFalse(rtn3Rs.isRuleLinked());
    // Link in Rule3
    n6.assertObject(f1, context, wm);
    n7.assertObject(f1, context, wm);
    assertTrue(bm.getSegmentMemory().isSegmentLinked());
    assertTrue(rtn1Rs.isRuleLinked());
    assertTrue(rtn2Rs.isRuleLinked());
    assertTrue(rtn3Rs.isRuleLinked());
    // retract n2, should unlink all rules
    n2.retractRightTuple(f2.getFirstRightTuple(), context, wm);
    assertFalse(rtn1Rs.isRuleLinked());
    assertFalse(rtn2Rs.isRuleLinked());
    assertFalse(rtn3Rs.isRuleLinked());
}
Also used : DefaultFactHandle(org.drools.core.common.DefaultFactHandle) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 69 with DefaultFactHandle

use of org.drools.core.common.DefaultFactHandle in project drools by kiegroup.

the class DroolsJaxbHelperTest method testXsdModelInRule.

@Test
public void testXsdModelInRule() {
    // DRL rule that references object created in XSD
    final String s1 = "package test; " + "global java.util.List list; " + "rule Init when " + "then " + "  insert( new Sub() ); " + "  insert( new Message() ); " + "  insert( new Test() ); " + "  insert( new Left() ); " + "end\n" + "rule CheckSub when " + " $s : Sub() " + "then " + "  list.add( \"Sub\" );  " + "end\n" + "rule CheckMsg when " + " $s : Message() " + "then " + "  list.add( \"Message\" );  " + "end\n ";
    KieHelper kh = new KieHelper();
    kh.addContent(s1, ResourceType.DRL);
    // XSD that defines "Sub" class
    InputStream simpleXsdStream = getClass().getResourceAsStream(simpleXsdRelativePath);
    assertNotNull("Could not find resource: " + simpleXsdRelativePath, simpleXsdStream);
    BaseResource xsdResource = new InputStreamResource(simpleXsdStream);
    Options xjcOptions = new Options();
    xsdResource.setConfiguration(new JaxbConfigurationImpl(xjcOptions, "test-system-id"));
    kh.addResource(xsdResource, ResourceType.XSD);
    // Verify that build succeeded
    assertEquals(0, kh.verify().getMessages(Message.Level.ERROR).size());
    assertEquals(0, kh.verify().getMessages(Message.Level.WARNING).size());
    // Run rules
    KieSession ks = kh.build().newKieSession();
    List list = new ArrayList();
    ks.setGlobal("list", list);
    ks.fireAllRules();
    // Verify results
    assertEquals(2, list.size());
    assertTrue(list.containsAll(asList("Sub", "Message")));
    Collection<FactHandle> fhs = ks.getFactHandles();
    Iterator<FactHandle> iter = fhs.iterator();
    DefaultFactHandle subFh = null, msgFh = null, leftFh = null, testFh = null;
    while (iter.hasNext()) {
        DefaultFactHandle dfh = (DefaultFactHandle) iter.next();
        if (dfh.getObjectClassName().equals("test.Sub")) {
            subFh = dfh;
        } else if (dfh.getObjectClassName().equals("test.Message")) {
            msgFh = dfh;
        } else if (dfh.getObjectClassName().equals("test.Left")) {
            leftFh = dfh;
        } else if (dfh.getObjectClassName().equals("test.Test")) {
            testFh = dfh;
        } else {
            fail("Unexpected FH class: " + dfh.getObjectClassName());
        }
    }
    assertNotNull("No FactHandle for Sub found!", subFh);
    assertNotNull("No FactHandle for Message found!", msgFh);
    Object xsdObj = subFh.getObject();
    Class xsdClass = xsdObj.getClass();
    try {
        Method m2 = xsdClass.getMethod("getFld");
        assertNotNull(m2);
        assertEquals(String.class, m2.getReturnType());
        assertEquals(0, xsdClass.getFields().length);
        java.lang.reflect.Field[] declaredFields = xsdClass.getDeclaredFields();
        assertEquals(1, declaredFields.length);
        assertEquals("fld", declaredFields[0].getName());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    // "Message" has attribute 'mixed="true"' which means only one field "content"
    xsdObj = msgFh.getObject();
    xsdClass = xsdObj.getClass();
    try {
        Method m2 = xsdClass.getMethod("getContent");
        assertNotNull(m2);
        assertEquals(List.class, m2.getReturnType());
        assertEquals(0, xsdClass.getFields().length);
        java.lang.reflect.Field[] declaredFields = xsdClass.getDeclaredFields();
        assertEquals(1, declaredFields.length);
        assertEquals("content", declaredFields[0].getName());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
Also used : Options(com.sun.tools.xjc.Options) FactHandle(org.kie.api.runtime.rule.FactHandle) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) InputStream(java.io.InputStream) BaseResource(org.drools.core.io.impl.BaseResource) ArrayList(java.util.ArrayList) KieHelper(org.kie.internal.utils.KieHelper) Method(java.lang.reflect.Method) Field(org.drools.core.rule.ConsequenceMetaData.Field) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) Arrays.asList(java.util.Arrays.asList) InputStreamResource(org.drools.core.io.impl.InputStreamResource) JaxbConfigurationImpl(org.drools.core.builder.conf.impl.JaxbConfigurationImpl) Test(org.junit.Test)

Example 70 with DefaultFactHandle

use of org.drools.core.common.DefaultFactHandle in project drools by kiegroup.

the class ObjectMarshallingStrategyStoreTest method testMultipleObjectMarshallingStrategiesOfTheSameClassWithDifferentNames.

@Test
public void testMultipleObjectMarshallingStrategiesOfTheSameClassWithDifferentNames() throws IOException, ClassNotFoundException {
    Environment env = EnvironmentFactory.newEnvironment();
    final Thing entityOne = new Thing(1, "Object 1");
    final Thing entityTwo = new Thing(2, "Object 2");
    Collection srcItems = new ArrayList();
    srcItems.add(entityOne);
    srcItems.add(entityTwo);
    ObjectMarshallingStrategy[] strats = new ObjectMarshallingStrategy[] { new IdentityPlaceholderResolverStrategy("entityOne", new ObjectMarshallingStrategyAcceptor() {

        @Override
        public boolean accept(Object object) {
            return entityOne.equals(object);
        }
    }, Collections.singletonMap(entityOne.id, (Object) entityOne)), new IdentityPlaceholderResolverStrategy("entityTwo", new ObjectMarshallingStrategyAcceptor() {

        @Override
        public boolean accept(Object object) {
            return entityTwo.equals(object);
        }
    }, Collections.singletonMap(entityTwo.id, (Object) entityTwo)) };
    env.set(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES, strats);
    KieSessionConfiguration ksc = SessionConfiguration.newInstance();
    final KieBaseConfiguration kbconf = RuleBaseFactory.newKnowledgeBaseConfiguration();
    kbconf.setOption(EventProcessingOption.STREAM);
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(RuleBaseFactory.newRuleBase(kbconf));
    KieSession ks = kbase.newKieSession(ksc, env);
    ks.insert(entityOne);
    ks.insert(entityTwo);
    ProtobufMarshaller marshaller = (ProtobufMarshaller) MarshallerFactory.newMarshaller(kbase, strats);
    // Serialize object
    final byte[] b1;
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        marshaller.marshall(bos, ks, System.currentTimeMillis());
        b1 = bos.toByteArray();
        bos.close();
    }
    // Deserialize object
    StatefulKnowledgeSession ksession2;
    {
        ByteArrayInputStream bais = new ByteArrayInputStream(b1);
        try {
            ksession2 = marshaller.unmarshall(bais, ks.getSessionConfiguration(), ks.getEnvironment());
            Collection items = ksession2.getFactHandles();
            Assert.assertTrue(items.size() == 2);
            for (Object item : items) {
                FactHandle factHandle = (FactHandle) item;
                Assert.assertTrue(srcItems.contains(((DefaultFactHandle) factHandle).getObject()));
            }
        } catch (RuntimeException npe) {
            // Here ocurrs the bug that shows that NamedObjectMarshallingStrategies are required.
            Assert.fail("This error only happens if identity ObjectMarshallingStrategy use old name");
        } finally {
            bais.close();
        }
    }
}
Also used : ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) FactHandle(org.kie.api.runtime.rule.FactHandle) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) StatefulKnowledgeSession(org.kie.internal.runtime.StatefulKnowledgeSession) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KieBaseConfiguration(org.kie.api.KieBaseConfiguration) IdentityPlaceholderResolverStrategy(org.drools.serialization.protobuf.marshalling.IdentityPlaceholderResolverStrategy) ByteArrayInputStream(java.io.ByteArrayInputStream) Environment(org.kie.api.runtime.Environment) Collection(java.util.Collection) KieSession(org.kie.api.runtime.KieSession) KieSessionConfiguration(org.kie.api.runtime.KieSessionConfiguration) InternalKnowledgeBase(org.drools.kiesession.rulebase.InternalKnowledgeBase) ObjectMarshallingStrategyAcceptor(org.kie.api.marshalling.ObjectMarshallingStrategyAcceptor) Test(org.junit.Test)

Aggregations

DefaultFactHandle (org.drools.core.common.DefaultFactHandle)92 Test (org.junit.Test)78 InternalFactHandle (org.drools.core.common.InternalFactHandle)30 FactHandle (org.kie.api.runtime.rule.FactHandle)29 Cheese (org.drools.core.test.model.Cheese)24 ArrayList (java.util.ArrayList)23 ClassObjectType (org.drools.core.base.ClassObjectType)22 KieSession (org.kie.api.runtime.KieSession)19 FieldIndex (org.drools.core.util.AbstractHashTable.FieldIndex)18 RightTupleImpl (org.drools.core.reteoo.RightTupleImpl)16 Declaration (org.drools.core.rule.Declaration)15 RightTuple (org.drools.core.reteoo.RightTuple)14 InternalReadAccessor (org.drools.core.spi.InternalReadAccessor)14 StatefulKnowledgeSessionImpl (org.drools.core.impl.StatefulKnowledgeSessionImpl)13 StatefulKnowledgeSessionImpl (org.drools.kiesession.session.StatefulKnowledgeSessionImpl)13 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)12 Pattern (org.drools.core.rule.Pattern)12 Tuple (org.drools.core.spi.Tuple)12 TupleIndexHashTable (org.drools.core.util.index.TupleIndexHashTable)12 InternalKnowledgeBase (org.drools.kiesession.rulebase.InternalKnowledgeBase)11