Search in sources :

Example 31 with DefaultFactHandle

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

the class XStreamXMLTest method testGetFactHandlesExecutionResults.

@Test
public void testGetFactHandlesExecutionResults() {
    final Message msg = new Message("Hello World!");
    final FactHandle msgHandle = new DefaultFactHandle(1, null, 10, 10, 20, msg);
    final Message msg2 = new Message("Hello World again!");
    final FactHandle msgHandle2 = new DefaultFactHandle(2, null, 10, 10, 20, msg2);
    List<FactHandle> factHandleList = new ArrayList<FactHandle>();
    factHandleList.add(msgHandle);
    factHandleList.add(msgHandle2);
    HashMap<String, Object> factHandles = new LinkedHashMap<String, Object>();
    ExecutionResultImpl executionResult = new ExecutionResultImpl();
    executionResult.setFactHandles(factHandles);
    HashMap<String, Object> results = new LinkedHashMap<String, Object>();
    results.put("facts", factHandleList);
    executionResult.setResults(results);
    String xmlString = xstream.toXML(executionResult);
    Assert.assertEquals("<execution-results>\n" + "  <result identifier=\"facts\">\n" + "    <list>\n" + "      <fact-handle external-form=\"0:1:10:10:20:null:NON_TRAIT:org.drools.xml.support.XStreamXMLTest$Message\"/>\n" + "      <fact-handle external-form=\"0:2:10:10:20:null:NON_TRAIT:org.drools.xml.support.XStreamXMLTest$Message\"/>\n" + "    </list>\n" + "  </result>\n" + "</execution-results>", xmlString);
    ExecutionResultImpl executionResult2 = (ExecutionResultImpl) xstream.fromXML(xmlString);
    Assert.assertEquals(executionResult.getFactHandles().size(), executionResult2.getFactHandles().size());
    Assert.assertEquals(executionResult.getResults().size(), executionResult2.getResults().size());
}
Also used : DefaultFactHandle(org.drools.core.common.DefaultFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) ExecutionResultImpl(org.drools.core.runtime.impl.ExecutionResultImpl) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Test(org.junit.Test)

Example 32 with DefaultFactHandle

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

the class ProtobufInputMarshaller method readFactHandle.

public static InternalFactHandle readFactHandle(ProtobufMarshallerReaderContext context, EntryPoint entryPoint, FactHandle _handle) throws IOException, ClassNotFoundException {
    Object object = null;
    ObjectMarshallingStrategy strategy = null;
    if (_handle.hasStrategyIndex()) {
        strategy = context.getUsedStrategies().get(_handle.getStrategyIndex());
        object = strategy.unmarshal(context.getStrategyContexts().get(strategy), context, _handle.getObject().toByteArray(), (context.getKnowledgeBase() == null) ? null : context.getKnowledgeBase().getRootClassLoader());
    }
    EntryPointId confEP;
    if (entryPoint != null) {
        confEP = ((NamedEntryPoint) entryPoint).getEntryPoint();
    } else {
        confEP = context.getWorkingMemory().getEntryPoint();
    }
    ObjectTypeConf typeConf = context.getWorkingMemory().getObjectTypeConfigurationRegistry().getOrCreateObjectTypeConf(confEP, object);
    InternalFactHandle handle = null;
    switch(_handle.getType()) {
        case FACT:
            {
                handle = new DefaultFactHandle(_handle.getId(), object, _handle.getRecency(), (WorkingMemoryEntryPoint) entryPoint, typeConf != null && typeConf.isTrait());
                break;
            }
        case QUERY:
            {
                handle = new QueryElementFactHandle(object, _handle.getId(), _handle.getRecency());
                break;
            }
        case EVENT:
            {
                handle = new EventFactHandle(_handle.getId(), object, _handle.getRecency(), _handle.getTimestamp(), _handle.getDuration(), (WorkingMemoryEntryPoint) entryPoint, typeConf != null && typeConf.isTrait());
                ((EventFactHandle) handle).setExpired(_handle.getIsExpired());
                ((EventFactHandle) handle).setOtnCount(_handle.getOtnCount());
                // ((EventFactHandle) handle).setActivationsCount( _handle.getActivationsCount() );
                break;
            }
        default:
            {
                throw new IllegalStateException("Unable to marshal FactHandle, as type does not exist:" + _handle.getType());
            }
    }
    return handle;
}
Also used : DefaultFactHandle(org.drools.core.common.DefaultFactHandle) ObjectTypeConf(org.drools.core.reteoo.ObjectTypeConf) EntryPointId(org.drools.core.rule.EntryPointId) ObjectMarshallingStrategy(org.kie.api.marshalling.ObjectMarshallingStrategy) QueryElementFactHandle(org.drools.core.common.QueryElementFactHandle) EventFactHandle(org.drools.core.common.EventFactHandle) InternalFactHandle(org.drools.core.common.InternalFactHandle)

Example 33 with DefaultFactHandle

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

the class ProtobufOutputMarshaller method writeTruthMaintenanceSystem.

public static void writeTruthMaintenanceSystem(MarshallerWriteContext context, EntryPoint wmep, ProtobufMessages.EntryPoint.Builder _epb) throws IOException {
    TruthMaintenanceSystem tms = TruthMaintenanceSystemFactory.get().getOrCreateTruthMaintenanceSystem((NamedEntryPoint) wmep);
    ObjectHashMap justifiedMap = tms.getEqualityKeyMap();
    if (!justifiedMap.isEmpty()) {
        EqualityKey[] keys = new EqualityKey[justifiedMap.size()];
        org.drools.core.util.Iterator it = justifiedMap.iterator();
        int i = 0;
        for (org.drools.core.util.ObjectHashMap.ObjectEntry entry = (org.drools.core.util.ObjectHashMap.ObjectEntry) it.next(); entry != null; entry = (org.drools.core.util.ObjectHashMap.ObjectEntry) it.next()) {
            EqualityKey key = (EqualityKey) entry.getKey();
            keys[i++] = key;
        }
        Arrays.sort(keys, EqualityKeySorter.instance);
        ProtobufMessages.TruthMaintenanceSystem.Builder _tms = ProtobufMessages.TruthMaintenanceSystem.newBuilder();
        // write the assert map of Equality keys
        for (EqualityKey key : keys) {
            ProtobufMessages.EqualityKey.Builder _key = ProtobufMessages.EqualityKey.newBuilder();
            _key.setStatus(key.getStatus());
            _key.setHandleId(key.getFactHandle().getId());
            if (key.size() > 1) {
                // add all the other key's if they exist
                FastIterator keyIter = key.fastIterator();
                for (DefaultFactHandle handle = key.getFirst().getNext(); handle != null; handle = (DefaultFactHandle) keyIter.next(handle)) {
                    _key.addOtherHandle(handle.getId());
                }
            }
            if (((TruthMaintenanceSystemEqualityKey) key).getBeliefSet() != null) {
                writeBeliefSet(context, ((TruthMaintenanceSystemEqualityKey) key).getBeliefSet(), _key);
            }
            _tms.addKey(_key.build());
        }
        _epb.setTms(_tms.build());
    }
}
Also used : TruthMaintenanceSystem(org.drools.core.common.TruthMaintenanceSystem) ObjectHashMap(org.drools.core.util.ObjectHashMap) WorkingMemoryEntryPoint(org.drools.core.WorkingMemoryEntryPoint) NamedEntryPoint(org.drools.kiesession.entrypoints.NamedEntryPoint) EntryPoint(org.kie.api.runtime.rule.EntryPoint) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) TruthMaintenanceSystemEqualityKey(org.drools.tms.TruthMaintenanceSystemEqualityKey) EqualityKey(org.drools.core.common.EqualityKey) FastIterator(org.drools.core.util.FastIterator)

Example 34 with DefaultFactHandle

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

the class CepEspTest method testDisconnectedEventFactHandle.

@Test
public void testDisconnectedEventFactHandle() {
    // DROOLS-924
    final String drl = "declare String \n" + "  @role(event)\n" + "end\n";
    final KieBase kbase = KieBaseUtil.getKieBaseFromKieModuleFromDrl("cep-esp-test", kieBaseTestConfiguration, drl);
    final KieSession ksession = kbase.newKieSession();
    try {
        final DefaultFactHandle helloHandle = (DefaultFactHandle) ksession.insert("hello");
        final DefaultFactHandle goodbyeHandle = (DefaultFactHandle) ksession.insert("goodbye");
        FactHandle key = DefaultFactHandle.createFromExternalFormat(helloHandle.toExternalForm());
        assertTrue("FactHandle not deserialized as EventFactHandle", key instanceof EventFactHandle);
        assertEquals("hello", ksession.getObject(key));
        key = DefaultFactHandle.createFromExternalFormat(goodbyeHandle.toExternalForm());
        assertTrue("FactHandle not deserialized as EventFactHandle", key instanceof EventFactHandle);
        assertEquals("goodbye", ksession.getObject(key));
    } finally {
        ksession.dispose();
    }
}
Also used : DefaultFactHandle(org.drools.core.common.DefaultFactHandle) InternalFactHandle(org.drools.core.common.InternalFactHandle) EventFactHandle(org.drools.core.common.EventFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) KieBase(org.kie.api.KieBase) EventFactHandle(org.drools.core.common.EventFactHandle) KieSession(org.kie.api.runtime.KieSession) Test(org.junit.Test)

Example 35 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 ";
    List<Resource> resources = KieUtil.getResourcesFromDrls(s1);
    // XSD that defines "Sub" class
    InputStream simpleXsdStream = getClass().getResourceAsStream(simpleXsdRelativePath);
    assertNotNull("Could not find resource: " + simpleXsdRelativePath, simpleXsdStream);
    BaseResource xsdResource = new InputStreamResource(simpleXsdStream);
    xsdResource.setResourceType(ResourceType.XSD);
    xsdResource.setSourcePath(TestConstants.TEST_RESOURCES_FOLDER + simpleXsdRelativePath);
    Options xjcOptions = new Options();
    xsdResource.setConfiguration(new JaxbConfigurationImpl(xjcOptions, "test-system-id"));
    resources.add(xsdResource);
    KieBase kbase = KieBaseUtil.getKieBaseFromResources(kieBaseTestConfiguration, resources.toArray(new Resource[] {}));
    KieSession ks = kbase.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) BaseResource(org.drools.core.io.impl.BaseResource) InputStreamResource(org.drools.core.io.impl.InputStreamResource) Resource(org.kie.api.io.Resource) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) KieBase(org.kie.api.KieBase) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) Arrays.asList(java.util.Arrays.asList) List(java.util.List) InputStreamResource(org.drools.core.io.impl.InputStreamResource) JaxbConfigurationImpl(org.drools.core.builder.conf.impl.JaxbConfigurationImpl) 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