Search in sources :

Example 21 with TraitableBean

use of org.drools.core.factmodel.traits.TraitableBean in project drools by kiegroup.

the class LogicalTraitTest method testShadowAliasClassOnTraitLogicalRetract.

@Test
public void testShadowAliasClassOnTraitLogicalRetract() {
    String drl = "package org.drools.test; \n" + "import org.drools.core.factmodel.traits.*; \n" + "import org.drools.core.factmodel.traits.Trait; \n" + "" + "global java.util.List list; \n" + "" + "declare trait X \n" + "  fld : K \n" + "  fld2 : K \n" + "end \n" + "" + "declare trait W \n" + "  fld : Q \n" + "end \n" + "declare trait V \n" + "  fld2 : T \n" + "end \n" + "" + "declare Y \n" + "@Traitable( logical = true ) \n" + "  fld : T \n" + "  fld2 : Q \n" + "end \n" + "" + "declare trait T @Trait( logical=true ) id : int end \n" + "declare trait Q @Trait( logical=true ) id : int end \n" + "declare K @Traitable() id : int end \n" + "" + "rule Don \n" + "when \n" + "  $s : String( this == \"go\" ) \n" + "then \n" + "  K k1 = new K( 1 ); \n" + "  K k2 = new K( 2 ); \n" + "  T t = don( k1, T.class ); \n" + "  Q q = don( k2, Q.class ); \n" + "  Y y = new Y( t, q ); \n" + "  insert( y ); \n" + "" + "  don( y, X.class, true ); \n" + "end \n" + "" + "rule Check \n" + "when \n" + "  String( this == \"go\" ) \n" + "  $x : X( $f1 : fld, $f2 : fld2 ) \n" + "then \n" + "  list.add( $f1.getId() );" + "  list.add( $f2.getId() );" + "end \n" + "" + "rule Check2\n" + "when \n" + "  not String( this == \"go\" ) \n" + "  $x : Y( $f1 : fld, $f2 : fld2 ) \n" + "then \n" + "  list.add( $f1.getId() );" + "  list.add( $f2.getId() );" + "end \n" + "";
    KnowledgeBuilder kbuilderImpl = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilderImpl.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
    if (kbuilderImpl.hasErrors()) {
        fail(kbuilderImpl.getErrors().toString());
    }
    InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addPackages(kbuilderImpl.getKnowledgePackages());
    TraitFactory.setMode(mode, kbase);
    KieSession ks = kbase.newKieSession();
    ArrayList list = new ArrayList();
    ks.setGlobal("list", list);
    FactHandle handle = ks.insert("go");
    ks.fireAllRules();
    assertEquals(Arrays.asList(1, 2), list);
    ks.retract(handle);
    ks.fireAllRules();
    for (Object o : ks.getObjects(new ClassObjectFilter(ks.getKieBase().getFactType("org.drools.test", "Y").getFactClass()))) {
        assertTrue(o instanceof TraitableBean);
    }
    try {
        ks = SerializationHelper.getSerialisedStatefulKnowledgeSession(ks, true);
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    System.out.println(list);
    assertEquals(Arrays.asList(1, 2, 1, 2), list);
}
Also used : KnowledgeBuilder(org.kie.internal.builder.KnowledgeBuilder) ClassObjectFilter(org.kie.api.runtime.ClassObjectFilter) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) ArrayList(java.util.ArrayList) KieSession(org.kie.api.runtime.KieSession) TraitableBean(org.drools.core.factmodel.traits.TraitableBean) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 22 with TraitableBean

use of org.drools.core.factmodel.traits.TraitableBean in project drools by kiegroup.

the class NamedEntryPoint method update.

public InternalFactHandle update(InternalFactHandle handle, final Object object, final BitMask mask, final Class<?> modifiedClass, final Activation activation) {
    try {
        this.lock.lock();
        this.wm.startOperation();
        this.kBase.executeQueuedActions();
        // the handle might have been disconnected, so reconnect if it has
        if (handle.isDisconnected()) {
            handle = this.objectStore.reconnect(handle);
        }
        final Object originalObject = handle.getObject();
        if (handle.getEntryPoint() != this) {
            throw new IllegalArgumentException("Invalid Entry Point. You updated the FactHandle on entry point '" + handle.getEntryPoint().getEntryPointId() + "' instead of '" + getEntryPointId() + "'");
        }
        final ObjectTypeConf typeConf = getObjectTypeConfigurationRegistry().getObjectTypeConf(this.entryPoint, object);
        if (handle.getId() == -1 || object == null || handle.isExpired()) {
            // the handle is invalid, most likely already retracted, so return and we cannot assert a null object
            return handle;
        }
        if (originalObject != object || !AssertBehaviour.IDENTITY.equals(this.kBase.getConfiguration().getAssertBehaviour())) {
            this.objectStore.updateHandle(handle, object);
        }
        this.handleFactory.increaseFactHandleRecency(handle);
        final PropagationContext propagationContext = pctxFactory.createPropagationContext(this.wm.getNextPropagationIdCounter(), PropagationContext.Type.MODIFICATION, activation == null ? null : activation.getRule(), activation == null ? null : activation.getTuple().getTupleSink(), handle, entryPoint, mask, modifiedClass, null);
        if (typeConf.isTMSEnabled()) {
            EqualityKey newKey = tms.get(object);
            EqualityKey oldKey = handle.getEqualityKey();
            if ((oldKey.getStatus() == EqualityKey.JUSTIFIED || oldKey.getBeliefSet() != null) && newKey != oldKey) {
                // Mixed stated and justified, we cannot have updates untill we figure out how to use this.
                throw new IllegalStateException("Currently we cannot modify something that has mixed stated and justified equal objects. " + "Rule " + activation.getRule().getName() + " attempted an illegal operation");
            }
            if (newKey == null) {
                oldKey.removeFactHandle(handle);
                newKey = new EqualityKey(handle, // updates are always stated
                EqualityKey.STATED);
                handle.setEqualityKey(newKey);
                getTruthMaintenanceSystem().put(newKey);
            } else if (newKey != oldKey) {
                oldKey.removeFactHandle(handle);
                handle.setEqualityKey(newKey);
                newKey.addFactHandle(handle);
            }
            // If the old equality key is now empty, and no justified entries, remove it
            if (oldKey.isEmpty() && oldKey.getLogicalFactHandle() == null) {
                getTruthMaintenanceSystem().remove(oldKey);
            }
        }
        if (handle.isTraitable() && object != originalObject && object instanceof TraitableBean && originalObject instanceof TraitableBean) {
            this.traitHelper.replaceCore(handle, object, originalObject, propagationContext.getModificationMask(), object.getClass(), activation);
        }
        update(handle, object, originalObject, typeConf, propagationContext);
    } finally {
        this.wm.endOperation();
        this.lock.unlock();
    }
    return handle;
}
Also used : ObjectTypeConf(org.drools.core.reteoo.ObjectTypeConf) PropagationContext(org.drools.core.spi.PropagationContext) TraitableBean(org.drools.core.factmodel.traits.TraitableBean)

Example 23 with TraitableBean

use of org.drools.core.factmodel.traits.TraitableBean in project drools by kiegroup.

the class TraitHelper method extractTrait.

public static <K> K extractTrait(InternalFactHandle handle, Class<K> klass) {
    TraitableBean tb;
    if (handle.isTraitable()) {
        tb = (TraitableBean) handle.getObject();
    } else if (handle.isTraiting()) {
        tb = ((TraitProxy) handle.getObject()).getObject();
    } else {
        return null;
    }
    K k = (K) tb.getTrait(klass.getCanonicalName());
    if (k != null) {
        return k;
    }
    for (Object t : tb.getMostSpecificTraits()) {
        if (klass.isAssignableFrom(t.getClass())) {
            return (K) t;
        }
    }
    return null;
}
Also used : TraitProxy(org.drools.core.factmodel.traits.TraitProxy) TraitableBean(org.drools.core.factmodel.traits.TraitableBean)

Example 24 with TraitableBean

use of org.drools.core.factmodel.traits.TraitableBean in project drools by kiegroup.

the class TraitHelper method makeTraitable.

private <K> TraitableBean makeTraitable(K core, TraitFactory builder, boolean logical, Activation activation) {
    boolean needsWrapping = !(core instanceof TraitableBean);
    ClassDefinition coreDef = lookupClassDefinition(core);
    TraitableBean<K, ? extends TraitableBean> inner = needsWrapping ? builder.asTraitable(core, coreDef) : (TraitableBean<K, ? extends TraitableBean>) core;
    if (needsWrapping) {
        InternalFactHandle h = (InternalFactHandle) lookupFactHandle(core);
        WorkingMemoryEntryPoint ep = h != null ? h.getEntryPoint() : ((StatefulKnowledgeSessionImpl) workingMemory).getEntryPoint("DEFAULT");
        ObjectTypeConfigurationRegistry reg = ep.getObjectTypeConfigurationRegistry();
        ObjectTypeConf coreConf = reg.getObjectTypeConf(ep.getEntryPoint(), core);
        ObjectTypeConf innerConf = reg.getObjectTypeConf(ep.getEntryPoint(), inner);
        if (coreConf.isTMSEnabled()) {
            innerConf.enableTMS();
        }
        if (inner._getFieldTMS() != null && inner._getFieldTMS().needsInit()) {
            inner._getFieldTMS().init(workingMemory);
        }
    } else {
        TraitFieldTMS ftms = inner._getFieldTMS();
        if (ftms != null) {
            FactHandle handle = lookupFactHandle(inner);
            if (handle == null) {
                handle = this.workingMemory.insert(inner, false, activation.getRule(), activation.getTuple().getTupleSink());
            }
            if (ftms.needsInit()) {
                ftms.init(workingMemory);
            }
        }
    }
    return inner;
}
Also used : ObjectTypeConf(org.drools.core.reteoo.ObjectTypeConf) TraitFieldTMS(org.drools.core.factmodel.traits.TraitFieldTMS) InternalFactHandle(org.drools.core.common.InternalFactHandle) FactHandle(org.kie.api.runtime.rule.FactHandle) TraitableBean(org.drools.core.factmodel.traits.TraitableBean) ClassDefinition(org.drools.core.factmodel.ClassDefinition) InternalFactHandle(org.drools.core.common.InternalFactHandle) WorkingMemoryEntryPoint(org.drools.core.WorkingMemoryEntryPoint) InternalWorkingMemoryEntryPoint(org.drools.core.common.InternalWorkingMemoryEntryPoint) ObjectTypeConfigurationRegistry(org.drools.core.common.ObjectTypeConfigurationRegistry)

Example 25 with TraitableBean

use of org.drools.core.factmodel.traits.TraitableBean in project drools by kiegroup.

the class TraitHelper method replaceCore.

public void replaceCore(InternalFactHandle handle, Object object, Object originalObject, BitMask modificationMask, Class<? extends Object> aClass, Activation activation) {
    TraitableBean src = (TraitableBean) originalObject;
    TraitableBean tgt = (TraitableBean) object;
    tgt._setTraitMap(src._getTraitMap());
    tgt._setDynamicProperties(src._getDynamicProperties());
    tgt._setFieldTMS(src._getFieldTMS());
    updateTraits(handle, modificationMask, object.getClass(), activation);
}
Also used : TraitableBean(org.drools.core.factmodel.traits.TraitableBean)

Aggregations

TraitableBean (org.drools.core.factmodel.traits.TraitableBean)27 Test (org.junit.Test)18 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)17 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)17 TraitProxy (org.drools.core.factmodel.traits.TraitProxy)13 TraitFactory (org.drools.core.factmodel.traits.TraitFactory)11 ArrayList (java.util.ArrayList)10 ByteArrayResource (org.drools.core.io.impl.ByteArrayResource)10 ClassPathResource (org.drools.core.io.impl.ClassPathResource)10 LogicalTypeInconsistencyException (org.drools.core.factmodel.traits.LogicalTypeInconsistencyException)9 KnowledgeBaseImpl (org.drools.core.impl.KnowledgeBaseImpl)9 FactType (org.kie.api.definition.type.FactType)9 Resource (org.kie.api.io.Resource)9 KieSession (org.kie.api.runtime.KieSession)8 BitSet (java.util.BitSet)6 StatelessKieSession (org.kie.api.runtime.StatelessKieSession)6 Collection (java.util.Collection)5 InternalFactHandle (org.drools.core.common.InternalFactHandle)4 ClassObjectFilter (org.kie.api.runtime.ClassObjectFilter)4 HashMap (java.util.HashMap)3