Esempio n. 1
0
  public static void writeLeftTuples(
      MarshallerWriteContext context, InternalFactHandle[] factHandles) throws IOException {
    ObjectOutputStream stream = context.stream;
    InternalWorkingMemory wm = context.wm;

    // Write out LeftTuples
    // context.out.println( "LeftTuples Start" );
    for (InternalFactHandle handle : factHandles) {
      // InternalFactHandle handle = (InternalFactHandle) it.next();

      for (LeftTuple leftTuple = handle.getFirstLeftTuple();
          leftTuple != null;
          leftTuple = (LeftTuple) leftTuple.getLeftParentNext()) {
        stream.writeShort(PersisterEnums.LEFT_TUPLE);
        int sinkId = leftTuple.getLeftTupleSink().getId();
        stream.writeInt(sinkId);
        stream.writeInt(handle.getId());

        // context.out.println( "LeftTuple sinkId:" + leftTuple.getLeftTupleSink().getId() + "
        // handleId:" + handle.getId() );
        writeLeftTuple(leftTuple, context, true);
      }
    }

    stream.writeShort(PersisterEnums.END);
    // context.out.println( "LeftTuples End" );
  }
Esempio n. 2
0
  private void addMatch(
      final LeftTuple leftTuple,
      final RightTuple rightTuple,
      final LeftTuple currentLeftChild,
      final LeftTuple currentRightChild,
      final InternalWorkingMemory workingMemory,
      final AccumulateMemory memory,
      final AccumulateContext accresult,
      final boolean useLeftMemory) {
    LeftTuple tuple = leftTuple;
    InternalFactHandle handle = rightTuple.getFactHandle();
    if (this.unwrapRightObject) {
      // if there is a subnetwork, handle must be unwrapped
      tuple = (LeftTuple) handle.getObject();
      // handle = tuple.getLastHandle();
    }
    this.accumulate.accumulate(
        memory.workingMemoryContext, accresult.context, tuple, handle, workingMemory);

    // in sequential mode, we don't need to keep record of matched tuples
    if (useLeftMemory) {
      // linking left and right by creating a new left tuple
      createLeftTuple(leftTuple, rightTuple, currentLeftChild, currentRightChild, this, true);
    }
  }
  /**
   * Retract the <code>FactHandleimpl</code> from the <code>Rete</code> network. Also remove the
   * <code>FactHandleImpl</code> from the node memory.
   *
   * @param rightTuple The fact handle.
   * @param object The object to assert.
   * @param workingMemory The working memory session.
   */
  public void retractObject(
      final InternalFactHandle factHandle,
      final PropagationContext context,
      final InternalWorkingMemory workingMemory) {

    if (context.getType() == PropagationContext.MODIFICATION
        && this.skipOnModify
        && context.getDormantActivations() == 0) {
      return;
    }

    if (this.objectMemoryEnabled) {
      final ObjectHashSet memory = (ObjectHashSet) workingMemory.getNodeMemory(this);
      memory.remove(factHandle);
    }

    for (RightTuple rightTuple = factHandle.getRightTuple();
        rightTuple != null;
        rightTuple = (RightTuple) rightTuple.getHandleNext()) {
      rightTuple.getRightTupleSink().retractRightTuple(rightTuple, context, workingMemory);
    }
    factHandle.setRightTuple(null);

    for (LeftTuple leftTuple = factHandle.getLeftTuple();
        leftTuple != null;
        leftTuple = (LeftTuple) leftTuple.getLeftParentNext()) {
      leftTuple.getLeftTupleSink().retractLeftTuple(leftTuple, context, workingMemory);
    }
    factHandle.setLeftTuple(null);
  }
Esempio n. 4
0
 /**
  * OTN needs to override remove to avoid releasing the node ID, since OTN are never removed from
  * the rulebase in the current implementation
  */
 protected void doRemove(
     final RuleRemovalContext context,
     final ReteooBuilder builder,
     final BaseNode node,
     final InternalWorkingMemory[] workingMemories) {
   if (context.getCleanupAdapter() != null) {
     for (InternalWorkingMemory workingMemory : workingMemories) {
       CleanupAdapter adapter = context.getCleanupAdapter();
       final ObjectHashSet memory = (ObjectHashSet) workingMemory.getNodeMemory(this);
       Iterator it = memory.iterator();
       for (ObjectEntry entry = (ObjectEntry) it.next();
           entry != null;
           entry = (ObjectEntry) it.next()) {
         InternalFactHandle handle = (InternalFactHandle) entry.getValue();
         for (LeftTuple leftTuple = handle.getFirstLeftTuple();
             leftTuple != null;
             leftTuple = leftTuple.getLeftParentNext()) {
           adapter.cleanUp(leftTuple, workingMemory);
         }
       }
     }
     context.setCleanupAdapter(null);
   }
   if (!node.isInUse()) {
     removeObjectSink((ObjectSink) node);
   }
 }
  /**
   *
   *
   * <pre>
   *
   *
   *                ( Cheese (type &quot;cheddar&quot;) )
   *
   *
   * </pre>
   *
   * This is currently the same as using a ReturnValueConstraint just that it doesn't need any
   * requiredDeclarations
   *
   * @throws IntrospectionException
   */
  public void testLiteralConstraint() throws IntrospectionException {
    final ReteooRuleBase ruleBase = (ReteooRuleBase) RuleBaseFactory.newRuleBase();
    final InternalWorkingMemory workingMemory =
        (InternalWorkingMemory) ruleBase.newStatefulSession();

    final ClassFieldExtractor extractor =
        cache.getExtractor(Cheese.class, "type", getClass().getClassLoader());

    final FieldValue field = FieldFactory.getFieldValue("cheddar");

    final Evaluator evaluator = ValueType.STRING_TYPE.getEvaluator(Operator.EQUAL);

    final LiteralConstraint constraint = new LiteralConstraint(extractor, evaluator, field);
    final ContextEntry context = constraint.createContextEntry();

    final Cheese cheddar = new Cheese("cheddar", 5);

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

    // check constraint
    assertTrue(constraint.isAllowed(cheddarHandle.getObject(), workingMemory, context));

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

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

    // check constraint
    assertFalse(constraint.isAllowed(stiltonHandle.getObject(), workingMemory, context));
  }
Esempio n. 6
0
 public static Map<String, Object> valuesAsMap(
     Object object,
     InternalWorkingMemory workingMemory,
     LeftTuple leftTuple,
     Declaration[] declarations) {
   if (declarations.length == 0) {
     return null;
   }
   Map<String, Object> map = new HashMap<String, Object>();
   for (Declaration declaration : declarations) {
     if (leftTuple == null) {
       map.put(
           declaration.getBindingName(),
           declaration.getExtractor().getValue(workingMemory, object));
     } else {
       InternalFactHandle fact = leftTuple.get(declaration);
       map.put(
           declaration.getBindingName(),
           declaration
               .getExtractor()
               .getValue(workingMemory, fact != null ? fact.getObject() : object));
     }
   }
   return map;
 }
Esempio n. 7
0
  /**
   * When L&R Unlinking is enabled, updateSink() is used to populate a node's memory, but it has to
   * take into account if it's propagating.
   */
  private void updateLRUnlinking(
      final ObjectSink sink,
      final PropagationContext context,
      final InternalWorkingMemory workingMemory) {

    final ObjectHashSet memory = (ObjectHashSet) workingMemory.getNodeMemory(this);

    Iterator it = memory.iterator();

    InternalFactHandle ctxHandle = (InternalFactHandle) context.getFactHandle();

    if (!context.isPropagating(this)
        || (context.isPropagating(this) && context.shouldPropagateAll())) {

      for (ObjectEntry entry = (ObjectEntry) it.next();
          entry != null;
          entry = (ObjectEntry) it.next()) {
        // Assert everything
        sink.assertObject((InternalFactHandle) entry.getValue(), context, workingMemory);
      }

    } else {

      for (ObjectEntry entry = (ObjectEntry) it.next();
          entry != null;
          entry = (ObjectEntry) it.next()) {
        InternalFactHandle handle = (InternalFactHandle) entry.getValue();
        // Exclude the current fact propagation
        if (handle.getId() != ctxHandle.getId()) {
          sink.assertObject(handle, context, workingMemory);
        }
      }
    }
  }
  private static ProtobufMessages.NodeMemory writeRIANodeMemory(
      final int nodeId, final Memory memory) {
    // for RIA nodes, we need to store the ID of the created handles
    RIAMemory mem = (RIAMemory) memory;
    if (!mem.memory.isEmpty()) {
      ProtobufMessages.NodeMemory.RIANodeMemory.Builder _ria =
          ProtobufMessages.NodeMemory.RIANodeMemory.newBuilder();

      final org.drools.core.util.Iterator it = mem.memory.iterator();
      // iterates over all propagated handles and assert them to the new sink
      for (ObjectEntry entry = (ObjectEntry) it.next();
          entry != null;
          entry = (ObjectEntry) it.next()) {
        LeftTuple leftTuple = (LeftTuple) entry.getKey();
        InternalFactHandle handle = (InternalFactHandle) entry.getValue();
        FactHandle _handle =
            ProtobufMessages.FactHandle.newBuilder()
                .setId(handle.getId())
                .setRecency(handle.getRecency())
                .build();
        _ria.addContext(
            ProtobufMessages.NodeMemory.RIANodeMemory.RIAContext.newBuilder()
                .setTuple(PersisterHelper.createTuple(leftTuple))
                .setResultHandle(_handle)
                .build());
      }

      return ProtobufMessages.NodeMemory.newBuilder()
          .setNodeId(nodeId)
          .setNodeType(ProtobufMessages.NodeMemory.NodeType.RIA)
          .setRia(_ria.build())
          .build();
    }
    return null;
  }
Esempio n. 9
0
  /**
   * Removes a match between left and right tuple
   *
   * @param rightTuple
   * @param match
   * @param result
   */
  private void removeMatch(
      final RightTuple rightTuple,
      final LeftTuple match,
      final InternalWorkingMemory workingMemory,
      final AccumulateMemory memory,
      final AccumulateContext accctx,
      final boolean reaccumulate) {
    // save the matching tuple
    LeftTuple leftTuple = match.getLeftParent();

    if (match != null) {
      // removing link between left and right
      match.unlinkFromLeftParent();
      match.unlinkFromRightParent();
    }

    // if there is a subnetwork, we need to unwrap the object from inside the tuple
    InternalFactHandle handle = rightTuple.getFactHandle();
    LeftTuple tuple = leftTuple;
    if (this.unwrapRightObject) {
      tuple = (LeftTuple) handle.getObject();
      // handle = tuple.getLastHandle();
    }

    if (this.accumulate.supportsReverse()) {
      // just reverse this single match
      this.accumulate.reverse(
          memory.workingMemoryContext, accctx.context, tuple, handle, workingMemory);
    } else {
      // otherwise need to recalculate all matches for the given leftTuple
      if (reaccumulate) {
        reaccumulateForLeftTuple(leftTuple, workingMemory, memory, accctx);
      }
    }
  }
  public static void readTruthMaintenanceSystem(MarshallerReaderContext context)
      throws IOException {
    ObjectInputStream stream = context.stream;

    TruthMaintenanceSystem tms = context.wm.getTruthMaintenanceSystem();
    while (stream.readShort() == PersisterEnums.EQUALITY_KEY) {
      int status = stream.readInt();
      int factHandleId = stream.readInt();
      InternalFactHandle handle = (InternalFactHandle) context.handles.get(factHandleId);

      // ObjectTypeConf state is not marshalled, so it needs to be re-determined
      ObjectTypeConf typeConf =
          context
              .wm
              .getObjectTypeConfigurationRegistry()
              .getObjectTypeConf(context.wm.getEntryPoint(), handle.getObject());
      if (!typeConf.isTMSEnabled()) {
        typeConf.enableTMS();
      }

      EqualityKey key = new EqualityKey(handle, status);
      handle.setEqualityKey(key);
      while (stream.readShort() == PersisterEnums.FACT_HANDLE) {
        factHandleId = stream.readInt();
        handle = (InternalFactHandle) context.handles.get(factHandleId);
        key.addFactHandle(handle);
        handle.setEqualityKey(key);
      }
      tms.put(key);
    }
  }
 /**
  * @param wm
  * @param cheeseHandles
  * @param index
  */
 private InternalFactHandle updateHandle(final StatefulSession wm, final FactHandle handle) {
   for (Iterator it = wm.iterateFactHandles(); it.hasNext(); ) {
     InternalFactHandle newHandle = (InternalFactHandle) it.next();
     if (((InternalFactHandle) handle).getId() == newHandle.getId()) {
       return newHandle;
     }
   }
   return null;
 }
Esempio n. 12
0
  private static void writeFactHandle(
      MarshallerWriteContext context,
      ObjectOutputStream stream,
      ObjectMarshallingStrategyStore objectMarshallingStrategyStore,
      int type,
      InternalFactHandle handle)
      throws IOException {
    stream.writeInt(type);
    stream.writeInt(handle.getId());
    stream.writeLong(handle.getRecency());

    if (type == 2) {
      // is event
      EventFactHandle efh = (EventFactHandle) handle;
      stream.writeLong(efh.getStartTimestamp());
      stream.writeLong(efh.getDuration());
      stream.writeBoolean(efh.isExpired());
      stream.writeLong(efh.getActivationsCount());
    }

    // context.out.println( "Object : int:" + handle.getId() + " long:" + handle.getRecency() );
    // context.out.println( handle.getObject() );

    Object object = handle.getObject();

    // Old versions wrote -1 and tested >= 0 to see if there was a strategy available
    // Now, we write -2 to indicate that we write the strategy class name to the stream
    stream.writeInt(-2);
    if (object != null) {
      ObjectMarshallingStrategy strategy = objectMarshallingStrategyStore.getStrategyObject(object);

      String strategyClassName = strategy.getClass().getName();
      stream.writeUTF(strategyClassName);

      strategy.write(stream, object);
    } else {
      stream.writeUTF("");
    }

    if (handle.getEntryPoint() instanceof InternalWorkingMemoryEntryPoint) {
      String entryPoint =
          ((InternalWorkingMemoryEntryPoint) handle.getEntryPoint())
              .getEntryPoint()
              .getEntryPointId();
      if (entryPoint != null && !entryPoint.equals("")) {
        stream.writeBoolean(true);
        stream.writeUTF(entryPoint);
      } else {
        stream.writeBoolean(false);
      }
    } else {
      stream.writeBoolean(false);
    }
  }
  public static ReteooStatefulSession readSession(
      MarshallerReaderContext context,
      int id,
      ExecutorService executor,
      Environment environment,
      SessionConfiguration config)
      throws IOException, ClassNotFoundException {

    boolean multithread = context.readBoolean();

    long time = context.readLong();

    FactHandleFactory handleFactory =
        context.ruleBase.newFactHandleFactory(context.readInt(), context.readLong());

    long propagationCounter = context.readLong();

    InternalFactHandle initialFactHandle =
        new DefaultFactHandle(
            context.readInt(), // id
            InitialFactImpl.getInstance(),
            context.readLong(),
            null);

    context.handles.put(initialFactHandle.getId(), initialFactHandle);

    DefaultAgenda agenda =
        context
            .ruleBase
            .getConfiguration()
            .getComponentFactory()
            .getAgendaFactory()
            .createAgenda(context.ruleBase, false);

    readAgenda(context, agenda);
    ReteooStatefulSession session =
        new ReteooStatefulSession(
            id,
            context.ruleBase,
            executor,
            handleFactory,
            initialFactHandle,
            propagationCounter,
            config,
            agenda,
            environment);
    new StatefulKnowledgeSessionImpl(session);

    initialFactHandle.setEntryPoint(
        session.getEntryPoints().get(EntryPoint.DEFAULT.getEntryPointId()));

    return readSession(session, agenda, time, multithread, context);
  }
  public void modifyLeftTuple(
      LeftTuple leftTuple, PropagationContext context, InternalWorkingMemory workingMemory) {
    final ObjectHashMap memory = (ObjectHashMap) workingMemory.getNodeMemory(this);
    // add it to a memory mapping
    InternalFactHandle handle = (InternalFactHandle) memory.get(leftTuple);

    // propagate it
    for (RightTuple rightTuple = handle.getFirstRightTuple();
        rightTuple != null;
        rightTuple = (RightTuple) rightTuple.getHandleNext()) {
      rightTuple.getRightTupleSink().modifyRightTuple(rightTuple, context, workingMemory);
    }
  }
Esempio n. 15
0
    public void rowUpdated(
        final Rule rule,
        final LeftTuple resultLeftTuple,
        final PropagationContext context,
        final InternalWorkingMemory workingMemory) {
      RightTuple rightTuple = (RightTuple) resultLeftTuple.getObject();
      if (rightTuple.getMemory() != null) {
        // Already sheduled as an insert
        return;
      }

      rightTuple.setLeftTuple(null);
      resultLeftTuple.setObject(null);

      // We need to recopy everything back again, as we don't know what has or hasn't changed
      QueryTerminalNode node = (QueryTerminalNode) resultLeftTuple.getLeftTupleSink();
      Declaration[] decls = node.getDeclarations();
      InternalFactHandle rootHandle = resultLeftTuple.get(0);
      DroolsQuery query = (DroolsQuery) rootHandle.getObject();

      Object[] objects = new Object[query.getElements().length];

      Declaration decl;
      for (int i = 0, length = this.variables.length; i < length; i++) {
        decl = decls[this.variables[i]];
        objects[this.variables[i]] =
            decl.getValue(workingMemory, resultLeftTuple.get(decl).getObject());
      }

      QueryElementFactHandle handle = (QueryElementFactHandle) rightTuple.getFactHandle();

      handle.setRecency(workingMemory.getFactHandleFactory().getAtomicRecency().incrementAndGet());
      handle.setObject(objects);

      if (query.isOpen()) {
        rightTuple.setLeftTuple(resultLeftTuple);
        resultLeftTuple.setObject(rightTuple);
      }

      // Don't need to recreate child links, as they will already be there form the first "add"

      RightTupleList rightTuples = query.getResultUpdateRightTupleList();
      if (rightTuples == null) {
        rightTuples = new RightTupleList();
        query.setResultUpdateRightTupleList(rightTuples);
        QueryResultUpdateAction updateAction =
            new QueryResultUpdateAction(context, this.factHandle, leftTuple, this.node);
        context.getQueue2().addFirst(updateAction);
      }
      rightTuples.add(rightTuple);
    }
Esempio n. 16
0
  public static void writeFactHandles(MarshallerWriteContext context, ObjectStore objectStore)
      throws IOException {
    ObjectOutputStream stream = context.stream;
    InternalWorkingMemory wm = context.wm;
    ObjectMarshallingStrategyStore objectMarshallingStrategyStore =
        context.objectMarshallingStrategyStore;

    List<InternalFactHandle> matchFactHandles = null;

    if (((InternalAgenda) wm.getAgenda()).isDeclarativeAgenda()) {
      ActivationIterator it = ActivationIterator.iterator(wm);
      matchFactHandles = new ArrayList<InternalFactHandle>(100);
      for (Activation item = (Activation) it.next(); item != null; item = (Activation) it.next()) {
        matchFactHandles.add(item.getFactHandle());
      }
    }

    stream.writeInt(
        objectStore.size() + ((matchFactHandles == null) ? 0 : matchFactHandles.size()));

    // Write out FactHandles
    for (InternalFactHandle handle : orderFacts(objectStore)) {
      // stream.writeShort( PersisterEnums.FACT_HANDLE );
      // InternalFactHandle handle = (InternalFactHandle) it.next();
      writeFactHandle(context, stream, objectMarshallingStrategyStore, handle);

      writeRightTuples(handle, context);
    }

    if (matchFactHandles != null) {
      for (InternalFactHandle handle : orderFacts(matchFactHandles)) {
        Object object = handle.getObject();
        handle.setObject(
            null); // we must set it to null as we don't want to write out the Activation
        writeFactHandle(context, stream, objectMarshallingStrategyStore, handle);
        handle.setObject(object); // restore object
        writeRightTuples(handle, context);
      }
    }

    // writeLeftTuples( context );
    writeLeftTuples(context, orderFacts(objectStore));

    if (matchFactHandles != null) {
      stream.writeBoolean(true);
      writeLeftTuples(context, orderFacts(matchFactHandles));
    } else {
      stream.writeBoolean(false);
    }
  }
Esempio n. 17
0
  /**
   * Propagate the <code>FactHandleimpl</code> through the <code>Rete</code> network. All <code>
   * FactHandleImpl</code> should be remembered in the node memory, so that later runtime rule
   * attachmnents can have the matched facts propagated to them.
   *
   * @param factHandle The fact handle.
   * @param object The object to assert.
   * @param workingMemory The working memory session.
   */
  public void assertObject(
      final InternalFactHandle factHandle,
      final PropagationContext context,
      final InternalWorkingMemory workingMemory) {

    if (objectMemoryEnabled && !(queryNode && !((DroolsQuery) factHandle.getObject()).isOpen())) {
      final ObjectHashSet memory = (ObjectHashSet) workingMemory.getNodeMemory(this);
      memory.add(factHandle, false);
    }

    if (compiledNetwork != null) {
      compiledNetwork.assertObject(factHandle, context, workingMemory);
    } else {

      context.setCurrentPropagatingOTN(this);
      this.sink.propagateAssertObject(factHandle, context, workingMemory);
    }

    if (this.objectType.isEvent()
        && this.expirationOffset >= 0
        && this.expirationOffset != Long.MAX_VALUE) {
      // schedule expiration
      WorkingMemoryReteExpireAction expire = new WorkingMemoryReteExpireAction(factHandle, this);
      TimerService clock = workingMemory.getTimerService();

      long nextTimestamp =
          Math.max(
              clock.getCurrentTime() + this.expirationOffset,
              ((EventFactHandle) factHandle).getStartTimestamp() + this.expirationOffset);
      JobContext jobctx = new ExpireJobContext(expire, workingMemory);
      JobHandle handle =
          clock.scheduleJob(job, jobctx, new PointInTimeTrigger(nextTimestamp, null, null));
      jobctx.setJobHandle(handle);
    }
  }
  public static void readRightTuple(MarshallerReaderContext context, InternalFactHandle factHandle)
      throws IOException {
    ObjectInputStream stream = context.stream;

    int sinkId = stream.readInt();
    RightTupleSink sink = (sinkId >= 0) ? (RightTupleSink) context.sinks.get(sinkId) : null;

    RightTuple rightTuple = new RightTuple(factHandle, sink);
    context.rightTuples.put(new RightTupleKey(factHandle.getId(), sink), rightTuple);

    if (sink != null) {
      BetaMemory memory = null;
      switch (sink.getType()) {
        case NodeTypeEnums.AccumulateNode:
          {
            memory = ((AccumulateMemory) context.wm.getNodeMemory((BetaNode) sink)).betaMemory;
            break;
          }
        default:
          {
            memory = (BetaMemory) context.wm.getNodeMemory((BetaNode) sink);
            break;
          }
      }
      memory.getRightTupleMemory().add(rightTuple);
      memory.linkLeft();
    }
  }
  public LeftTuple(
      final LeftTuple leftTuple,
      final RightTuple rightTuple,
      LeftTupleSink sink,
      boolean leftTupleMemoryEnabled) {
    this.handle = rightTuple.getFactHandle();
    this.index = leftTuple.index + 1;
    this.parent = leftTuple;
    this.recency = leftTuple.recency + this.handle.getRecency();
    this.hashCode = leftTuple.hashCode ^ (handle.hashCode() * 31);

    if (leftTupleMemoryEnabled) {
      this.rightParent = rightTuple;
      this.rightParentNext = this.rightParent.getBetaChildren();
      if (this.rightParentNext != null) {
        this.rightParentNext.rightParentPrevious = this;
      }
      this.rightParent.setBetaChildren(this);

      this.leftParent = leftTuple;
      this.leftParentNext = leftTuple.children;
      if (this.leftParentNext != null) {
        this.leftParentNext.leftParentPrevious = this;
      }
      this.leftParent.children = this;
    }

    this.sink = sink;
  }
  private static ProtobufMessages.NodeMemory writeQueryElementNodeMemory(
      final int nodeId, final Memory memory, final InternalWorkingMemory wm) {
    LeftTupleIterator it = LeftTupleIterator.iterator(wm, ((QueryElementNodeMemory) memory).node);

    ProtobufMessages.NodeMemory.QueryElementNodeMemory.Builder _query =
        ProtobufMessages.NodeMemory.QueryElementNodeMemory.newBuilder();
    for (LeftTuple leftTuple = (LeftTuple) it.next();
        leftTuple != null;
        leftTuple = (LeftTuple) it.next()) {
      InternalFactHandle handle = (InternalFactHandle) leftTuple.getObject();
      FactHandle _handle =
          ProtobufMessages.FactHandle.newBuilder()
              .setId(handle.getId())
              .setRecency(handle.getRecency())
              .build();

      ProtobufMessages.NodeMemory.QueryElementNodeMemory.QueryContext.Builder _context =
          ProtobufMessages.NodeMemory.QueryElementNodeMemory.QueryContext.newBuilder()
              .setTuple(PersisterHelper.createTuple(leftTuple))
              .setHandle(_handle);

      LeftTuple childLeftTuple = leftTuple.getFirstChild();
      while (childLeftTuple != null) {
        RightTuple rightParent = childLeftTuple.getRightParent();
        _context.addResult(
            ProtobufMessages.FactHandle.newBuilder()
                .setId(rightParent.getFactHandle().getId())
                .setRecency(rightParent.getFactHandle().getRecency())
                .build());
        while (childLeftTuple != null && childLeftTuple.getRightParent() == rightParent) {
          // skip to the next child that has a different right parent
          childLeftTuple = childLeftTuple.getLeftParentNext();
        }
      }
      _query.addContext(_context.build());
    }

    return _query.getContextCount() > 0
        ? ProtobufMessages.NodeMemory.newBuilder()
            .setNodeId(nodeId)
            .setNodeType(ProtobufMessages.NodeMemory.NodeType.QUERY_ELEMENT)
            .setQueryElement(_query.build())
            .build()
        : null;
  }
Esempio n. 21
0
  public static void writeInitialFactHandleLeftTuples(MarshallerWriteContext context)
      throws IOException {
    ObjectOutputStream stream = context.stream;

    // context.out.println( "InitialFact LeftTuples Start" );
    InternalFactHandle handle = context.wm.getInitialFactHandle();
    for (LeftTuple leftTuple = handle.getFirstLeftTuple();
        leftTuple != null;
        leftTuple = (LeftTuple) leftTuple.getLeftParentNext()) {
      stream.writeShort(PersisterEnums.LEFT_TUPLE);

      stream.writeInt(leftTuple.getLeftTupleSink().getId());
      // context.out.println( "LeftTuple sinkId:" + leftTuple.getLeftTupleSink().getId() );
      writeLeftTuple(leftTuple, context, true);
    }
    stream.writeShort(PersisterEnums.END);
    // context.out.println( "InitialFact LeftTuples End" );
  }
  // ------------------------------------------------------------
  // Constructors
  // ------------------------------------------------------------
  public LeftTuple(
      final InternalFactHandle factHandle, LeftTupleSink sink, boolean leftTupleMemoryEnabled) {
    this.handle = factHandle;
    this.recency = factHandle.getRecency();

    this.hashCode = handle.hashCode();

    if (leftTupleMemoryEnabled) {
      LeftTuple currentFirst = handle.getLeftTuple();
      if (currentFirst != null) {
        currentFirst.leftParentPrevious = this;
        this.leftParentNext = currentFirst;
      }

      handle.setLeftTuple(this);
    }
    this.sink = sink;
  }
    public boolean evaluateCachedLeft(
        InternalWorkingMemory workingMemory,
        VariableContextEntry context,
        InternalFactHandle right) {

      Object target = ((VariableRestriction.ObjectVariableContextEntry) context).left;
      Object source = right.getObject();

      return compare(source, target, workingMemory);
    }
Esempio n. 24
0
  public void modifyActivation(
      final InternalFactHandle factHandle,
      final PropagationContext context,
      final InternalWorkingMemory workingMemory) {
    if (activationNode == null) {
      this.activationNode = objectTypeNodes.get(ClassObjectType.Activation_ObjectType);
    }

    if (activationNode != null) {
      ModifyPreviousTuples modifyPreviousTuples =
          new ModifyPreviousTuples(factHandle.getFirstLeftTuple(), factHandle.getFirstRightTuple());
      factHandle.clearLeftTuples();
      factHandle.clearRightTuples();

      // There may be no queries defined
      this.activationNode.modifyObject(factHandle, modifyPreviousTuples, context, workingMemory);
      modifyPreviousTuples.retractTuples(context, workingMemory);
    }
  }
 private static ProtobufMessages.FactHandle.HandleType getHandleType(InternalFactHandle handle) {
   if (handle instanceof EventFactHandle) {
     return ProtobufMessages.FactHandle.HandleType.EVENT;
   } else if (handle instanceof QueryElementFactHandle) {
     return ProtobufMessages.FactHandle.HandleType.QUERY;
   } else if (handle.getObject() instanceof InitialFact) {
     return ProtobufMessages.FactHandle.HandleType.INITIAL_FACT;
   }
   return ProtobufMessages.FactHandle.HandleType.FACT;
 }
    public boolean evaluateCachedRight(
        InternalWorkingMemory workingMemory,
        VariableContextEntry context,
        InternalFactHandle left) {

      Object target = left.getObject();
      Object source = context.getObject();

      return compare(source, target, workingMemory);
    }
Esempio n. 27
0
 private void reaccumulateForLeftTuple(
     final LeftTuple leftTuple,
     final InternalWorkingMemory workingMemory,
     final AccumulateMemory memory,
     final AccumulateContext accctx) {
   this.accumulate.init(memory.workingMemoryContext, accctx.context, leftTuple, workingMemory);
   for (LeftTuple childMatch = getFirstMatch(leftTuple, accctx, false);
       childMatch != null;
       childMatch = childMatch.getLeftParentNext()) {
     InternalFactHandle childHandle = childMatch.getRightParent().getFactHandle();
     LeftTuple tuple = leftTuple;
     if (this.unwrapRightObject) {
       tuple = (LeftTuple) childHandle.getObject();
       childHandle = tuple.getLastHandle();
     }
     this.accumulate.accumulate(
         memory.workingMemoryContext, accctx.context, tuple, childHandle, workingMemory);
   }
 }
Esempio n. 28
0
 public void accumulate(
     Object workingMemoryContext,
     Object context,
     Tuple leftTuple,
     InternalFactHandle handle,
     Declaration[] declarations,
     Declaration[] innerDeclarations,
     WorkingMemory workingMemory)
     throws Exception {
   this.matchingObjects.add(handle.getObject());
 }
    public boolean evaluate(
        InternalWorkingMemory workingMemory,
        final InternalReadAccessor extractor1,
        final InternalFactHandle handle1,
        final InternalReadAccessor extractor2,
        final InternalFactHandle handle2) {
      if (extractor1.isNullValue(workingMemory, handle1.getObject())
          || extractor2.isNullValue(workingMemory, handle2.getObject())) {
        return false;
      }

      long distStart =
          ((EventFactHandle) handle1).getStartTimestamp()
              - ((EventFactHandle) handle2).getStartTimestamp();
      long distEnd =
          Math.abs(
              ((EventFactHandle) handle2).getEndTimestamp()
                  - ((EventFactHandle) handle1).getEndTimestamp());
      return this.getOperator().isNegated() ^ (distStart > 0 && distEnd <= this.endDev);
    }
  /**
   *
   *
   * <pre>
   *
   *
   *                type == &quot;cheddar&quot &amp;&amp; price &gt; 10
   *
   *
   * </pre>
   *
   * Test the use of the composite AND constraint. Composite AND constraints are only used when
   * nested inside other field constraints, as the top level AND is implicit
   *
   * @throws IntrospectionException
   */
  public void testCompositeAndConstraint() {
    final ReteooRuleBase ruleBase = (ReteooRuleBase) RuleBaseFactory.newRuleBase();
    final InternalWorkingMemory workingMemory =
        (InternalWorkingMemory) ruleBase.newStatefulSession();

    final ClassFieldExtractor extractor =
        cache.getExtractor(Cheese.class, "type", getClass().getClassLoader());

    final FieldValue field = FieldFactory.getFieldValue("cheddar");

    final Evaluator evaluator = ValueType.STRING_TYPE.getEvaluator(Operator.EQUAL);

    final LiteralConstraint constraint1 = new LiteralConstraint(extractor, evaluator, field);

    final ClassFieldExtractor priceExtractor =
        cache.getExtractor(Cheese.class, "price", getClass().getClassLoader());

    final FieldValue priceField = FieldFactory.getFieldValue(10);

    final Evaluator priceEvaluator = ValueType.INTEGER_TYPE.getEvaluator(Operator.GREATER);

    final LiteralConstraint constraint2 =
        new LiteralConstraint(priceExtractor, priceEvaluator, priceField);

    final Cheese cheddar = new Cheese("cheddar", 15);

    final AndConstraint constraint = new AndConstraint();
    constraint.addAlphaConstraint(constraint1);
    constraint.addAlphaConstraint(constraint2);

    final ContextEntry context = constraint.createContextEntry();

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

    // check constraint
    assertTrue(constraint.isAllowed(cheddarHandle.getObject(), workingMemory, context));

    cheddar.setPrice(5);
    ((ShadowProxy) cheddarHandle.getObject()).updateProxy();
    assertFalse(constraint.isAllowed(cheddarHandle.getObject(), workingMemory, context));

    cheddar.setType("stilton");
    ((ShadowProxy) cheddarHandle.getObject()).updateProxy();
    assertFalse(constraint.isAllowed(cheddarHandle.getObject(), workingMemory, context));

    cheddar.setPrice(15);
    ((ShadowProxy) cheddarHandle.getObject()).updateProxy();
    assertFalse(constraint.isAllowed(cheddarHandle.getObject(), workingMemory, context));
  }