private static void writeBeliefSet(
      MarshallerWriteContext context,
      BeliefSet beliefSet,
      org.drools.core.marshalling.impl.ProtobufMessages.EqualityKey.Builder _key)
      throws IOException {

    ProtobufMessages.BeliefSet.Builder _beliefSet = ProtobufMessages.BeliefSet.newBuilder();
    _beliefSet.setHandleId(beliefSet.getFactHandle().getId());

    ObjectMarshallingStrategyStore objectMarshallingStrategyStore =
        context.objectMarshallingStrategyStore;

    // for ( LinkedListEntry node = (LinkedListEntry) beliefSet.getFirst(); node != null; node =
    // (LinkedListEntry) node.getNext() ) {
    FastIterator it = beliefSet.iterator();
    for (LinkedListEntry node = (LinkedListEntry) beliefSet.getFirst();
        node != null;
        node = (LinkedListEntry) it.next(node)) {
      LogicalDependency belief = (LogicalDependency) node.getObject();
      ProtobufMessages.LogicalDependency.Builder _logicalDependency =
          ProtobufMessages.LogicalDependency.newBuilder();
      // _belief.setActivation( value )

      LogicalDependency dependency = (LogicalDependency) node.getObject();
      org.drools.core.spi.Activation activation = dependency.getJustifier();
      ProtobufMessages.Activation _activation =
          ProtobufMessages.Activation.newBuilder()
              .setPackageName(activation.getRule().getPackage())
              .setRuleName(activation.getRule().getName())
              .setTuple(PersisterHelper.createTuple(activation.getTuple()))
              .build();
      _logicalDependency.setActivation(_activation);

      if (belief.getObject() != null) {
        ObjectMarshallingStrategy strategy =
            objectMarshallingStrategyStore.getStrategyObject(belief.getObject());

        Integer index = context.getStrategyIndex(strategy);
        _logicalDependency.setObjectStrategyIndex(index.intValue());
        _logicalDependency.setObject(
            ByteString.copyFrom(
                strategy.marshal(
                    context.strategyContext.get(strategy), context, belief.getObject())));
      }

      if (belief.getValue() != null) {
        ObjectMarshallingStrategy strategy =
            objectMarshallingStrategyStore.getStrategyObject(belief.getValue());

        Integer index = context.getStrategyIndex(strategy);
        _logicalDependency.setValueStrategyIndex(index.intValue());
        _logicalDependency.setValue(
            ByteString.copyFrom(
                strategy.marshal(
                    context.strategyContext.get(strategy), context, belief.getValue())));
      }
      _beliefSet.addLogicalDependency(_logicalDependency.build());
    }
    _key.setBeliefSet(_beliefSet);
  }
 public boolean accept(
     Activation activation,
     PropagationContext context,
     InternalWorkingMemory workingMemory,
     TerminalNode rtn) {
   if (activation.isRuleAgendaItem()) {
     ActivationKey key =
         PersisterHelper.createActivationKey(
             activation.getRule().getPackageName(),
             activation.getRule().getName(),
             activation.getTuple());
     if (!this.rneActivations.containsKey(key)) {
       rneaToFire.add((RuleAgendaItem) activation);
     }
     return true;
   } else {
     ActivationKey key =
         PersisterHelper.createActivationKey(
             rtn.getRule().getPackageName(), rtn.getRule().getName(), activation.getTuple());
     // add the tuple to the cache for correlation
     this.tuplesCache.put(key, activation.getTuple());
     // check if there was an active activation for it
     return !this.dormantActivations.containsKey(key);
   }
 }
Exemple #3
0
 private boolean checkProcessInstance(Activation activation, long processInstanceId) {
   final Map<String, Declaration> declarations = activation.getSubRule().getOuterDeclarations();
   for (Declaration declaration : declarations.values()) {
     if ("processInstance".equals(declaration.getIdentifier())) {
       Object value =
           declaration.getValue(workingMemory, activation.getTuple().get(declaration).getObject());
       if (value instanceof ProcessInstance) {
         return ((ProcessInstance) value).getId() == processInstanceId;
       }
     }
   }
   return true;
 }
Exemple #4
0
  public Trigger createTrigger(Activation item, InternalWorkingMemory wm) {
    long timestamp = wm.getTimerService().getCurrentTime();
    String[] calendarNames = item.getRule().getCalendars();
    Calendars calendars = wm.getCalendars();

    Declaration[][] timerDeclrs = ((AgendaItem) item).getTerminalNode().getTimerDeclarations();

    ScheduledAgendaItem schItem = (ScheduledAgendaItem) item;
    DefaultJobHandle jh = null;
    if (schItem.getJobHandle() != null) {
      jh = (DefaultJobHandle) schItem.getJobHandle();
    }

    return createTrigger(timestamp, item.getTuple(), jh, calendarNames, calendars, timerDeclrs, wm);
  }
Exemple #5
0
  /** @inheritDoc */
  public boolean isRuleInstanceAgendaItem(
      String ruleflowGroupName, String ruleName, long processInstanceId) {

    RuleFlowGroup systemRuleFlowGroup = this.getRuleFlowGroup(ruleflowGroupName);

    Match[] matches = ((InternalAgendaGroup) systemRuleFlowGroup).getActivations();
    for (Match match : matches) {
      Activation act = (Activation) match;
      if (ruleName.equals(act.getRule().getName())) {
        if (checkProcessInstance(act, processInstanceId)) {
          return true;
        }
      }
    }
    return false;
  }
 public int compare(org.drools.core.spi.Activation o1, org.drools.core.spi.Activation o2) {
   int result = o1.getRule().getName().compareTo(o2.getRule().getName());
   if (result == 0) {
     LeftTuple t1 = o1.getTuple();
     LeftTuple t2 = o2.getTuple();
     while (result == 0 && t1 != null && t2 != null) {
       if (t1.getLastHandle() != null && t2.getLastHandle() != null) {
         // can be null for eval, not and exists that have no right input
         result = t1.getLastHandle().getId() - t2.getLastHandle().getId();
       }
       t1 = t1.getParent();
       t2 = t2.getParent();
     }
   }
   return result;
 }
 public boolean accept(final Activation activation) {
   Matcher matcher = pattern.matcher(activation.getRule().getName());
   if (matcher.matches()) {
     return this.accept;
   } else {
     return !this.accept;
   }
 }
 protected boolean checkProcessInstance(Activation activation) {
   final Map<?, ?> declarations = activation.getSubRule().getOuterDeclarations();
   for (Iterator<?> it = declarations.values().iterator(); it.hasNext(); ) {
     Declaration declaration = (Declaration) it.next();
     if ("processInstance".equals(declaration.getIdentifier())
         || "org.kie.api.runtime.process.WorkflowProcessInstance"
             .equals(declaration.getTypeName())) {
       Object value =
           declaration.getValue(
               ((StatefulKnowledgeSessionImpl) getProcessInstance().getKnowledgeRuntime())
                   .getInternalWorkingMemory(),
               ((InternalFactHandle) activation.getTuple().get(declaration)).getObject());
       if (value instanceof ProcessInstance) {
         return ((ProcessInstance) value).getId() == getProcessInstance().getId();
       }
     }
   }
   return true;
 }
Exemple #9
0
  public void cancelActivation(
      final LeftTuple leftTuple,
      final PropagationContext context,
      final InternalWorkingMemory workingMemory,
      final Activation activation,
      final TerminalNode rtn) {
    AgendaItem item = (AgendaItem) activation;
    item.removeAllBlockersAndBlocked(this);

    if (isDeclarativeAgenda() && activation.getFactHandle() == null) {
      // This a control rule activation, nothing to do except update counters. As control rules are
      // not in agenda-groups etc.
      return;
    } else {
      // we are retracting an actual Activation, so also remove it and it's handle from the WM.
      removeActivation(item);
    }

    if (activation.isQueued()) {
      // on fact expiration, we don't remove the activation, but let it fire
      if (context.getType() == PropagationContext.EXPIRATION
          && context.getFactHandleOrigin() != null) {
      } else {
        activation.remove();

        if (activation.getActivationGroupNode() != null) {
          activation.getActivationGroupNode().getActivationGroup().removeActivation(activation);
        }
        leftTuple.decreaseActivationCountForEvents();

        ((EventSupport) workingMemory)
            .getAgendaEventSupport()
            .fireActivationCancelled(activation, workingMemory, MatchCancelledCause.WME_MODIFY);
      }
    }

    if (item.getActivationUnMatchListener() != null) {
      item.getActivationUnMatchListener().unMatch(workingMemory.getKnowledgeRuntime(), item);
    }

    TruthMaintenanceSystemHelper.removeLogicalDependencies(activation, context, rtn.getRule());
  }
Exemple #10
0
  /*
   * (non-Javadoc)
   *
   * @see org.kie.common.AgendaI#clearActivationGroup(org.kie.spi.ActivationGroup)
   */
  public void clearAndCancelActivationGroup(final InternalActivationGroup activationGroup) {
    final EventSupport eventsupport = (EventSupport) this.workingMemory;

    activationGroup.setTriggeredForRecency(this.workingMemory.getFactHandleFactory().getRecency());

    for (final Iterator it = activationGroup.iterator(); it.hasNext(); ) {
      final ActivationGroupNode node = (ActivationGroupNode) it.next();
      final Activation activation = node.getActivation();
      activation.setActivationGroupNode(null);

      if (activation.isQueued()) {
        activation.setQueued(false);
        activation.remove();

        eventsupport
            .getAgendaEventSupport()
            .fireActivationCancelled(activation, this.workingMemory, MatchCancelledCause.CLEAR);
      }
    }
    activationGroup.reset();
  }
  private static void evaluateRuleActivations(StatefulKnowledgeSessionImpl wm) {
    // ET: NOTE: initially we were only resolving partially evaluated rules
    // but some tests fail because of that. Have to resolve all rule agenda items
    // in order to fix the tests

    // find all partially evaluated rule activations
    //        ActivationIterator it = ActivationIterator.iterator( wm );
    //        Set<String> evaluated = new HashSet<String>();
    //        for ( org.drools.core.spi.Activation item = (org.drools.core.spi.Activation)
    // it.next(); item != null; item = (org.drools.core.spi.Activation) it.next() ) {
    //            if ( !item.isRuleAgendaItem() ) {
    //                evaluated.add( item.getRule().getPackageName()+"."+item.getRule().getName() );
    //            }
    //        }
    // need to evaluate all lazy partially evaluated activations before serializing
    boolean dirty = true;
    while (dirty) {
      for (Activation activation : ((InternalAgenda) wm.getAgenda()).getActivations()) {
        if (activation
            .isRuleAgendaItem() /*&& evaluated.contains( activation.getRule().getPackageName()+"."+activation.getRule().getName() )*/) {
          // evaluate it
          ((RuleAgendaItem) activation).getRuleExecutor().reEvaluateNetwork(wm, null, false);
          ((RuleAgendaItem) activation).getRuleExecutor().removeRuleAgendaItemWhenEmpty(wm);
        }
      }
      dirty = false;
      if (wm.getKnowledgeBase().getConfiguration().isPhreakEnabled()) {
        // network evaluation with phreak and TMS may make previous processed rules dirty again, so
        // need to reprocess until all is flushed.
        for (Activation activation : ((InternalAgenda) wm.getAgenda()).getActivations()) {
          if (activation.isRuleAgendaItem()
              && ((RuleAgendaItem) activation).getRuleExecutor().isDirty()) {
            dirty = true;
            break;
          }
        }
      }
    }
  }
  private int fire(
      InternalWorkingMemory wm,
      AgendaFilter filter,
      int fireCount,
      int fireLimit,
      LinkedList<StackEntry> outerStack,
      InternalAgenda agenda,
      boolean fireUntilHalt) {
    int localFireCount = 0;
    if (!tupleList.isEmpty()) {
      RuleTerminalNode rtn = (RuleTerminalNode) pmem.getNetworkNode();

      if (!fireExitedEarly && isDeclarativeAgendaEnabled()) {
        // Network Evaluation can notify meta rules, which should be given a chance to fire first
        RuleAgendaItem nextRule = agenda.peekNextRule();
        if (!isHighestSalience(nextRule, ruleAgendaItem.getSalience())) {
          fireExitedEarly = true;
          return localFireCount;
        }
      }

      while (!tupleList.isEmpty()) {
        LeftTuple leftTuple;
        if (queue != null) {
          leftTuple = (LeftTuple) queue.dequeue();
          tupleList.remove(leftTuple);
        } else {
          leftTuple = tupleList.removeFirst();
          ((Activation) leftTuple).setQueued(false);
        }

        rtn =
            (RuleTerminalNode)
                leftTuple
                    .getSink(); // branches result in multiple RTN's for a given rule, so unwrap per
        // LeftTuple
        RuleImpl rule = rtn.getRule();

        PropagationContext pctx = leftTuple.getPropagationContext();
        pctx = RuleTerminalNode.findMostRecentPropagationContext(leftTuple, pctx);

        // check if the rule is not effective or
        // if the current Rule is no-loop and the origin rule is the same then return
        if (cancelAndContinue(wm, rtn, rule, leftTuple, pctx, filter)) {
          continue;
        }

        AgendaItem item = (AgendaItem) leftTuple;
        if (agenda.getActivationsFilter() != null
            && !agenda.getActivationsFilter().accept(item, wm, rtn)) {
          // only relevant for seralization, to not refire Matches already fired
          continue;
        }

        agenda.fireActivation(item);
        localFireCount++;

        if (rtn.getLeftTupleSource() == null) {
          break; // The activation firing removed this rule from the rule base
        }

        int salience =
            ruleAgendaItem.getSalience(); // dyanmic salience may have updated it, so get again.
        if (queue != null && !queue.isEmpty() && salience != queue.peek().getSalience()) {
          ruleAgendaItem.dequeue();
          ruleAgendaItem.setSalience(queue.peek().getSalience());
          ruleAgendaItem.getAgendaGroup().add(ruleAgendaItem);
          salience = ruleAgendaItem.getSalience();
        }

        RuleAgendaItem nextRule = agenda.peekNextRule();
        if (haltRuleFiring(nextRule, fireCount, fireLimit, localFireCount, agenda, salience)) {
          break; // another rule has high priority and is on the agenda, so evaluate it first
        }
        reEvaluateNetwork(wm, outerStack, fireUntilHalt);
        wm.executeQueuedActions();

        if (tupleList.isEmpty() && !outerStack.isEmpty()) {
          // the outer stack is nodes needing evaluation, once all rule firing is done
          // such as window expiration, which must be done serially
          StackEntry entry = outerStack.removeFirst();
          NETWORK_EVALUATOR.evalStackEntry(entry, outerStack, outerStack, this, wm);
        }
      }
    }

    removeRuleAgendaItemWhenEmpty(wm);

    fireExitedEarly = false;
    return localFireCount;
  }
Exemple #13
0
  /**
   * Fire this item.
   *
   * @param activation The activation to fire
   * @throws org.drools.core.spi.ConsequenceException If an error occurs while attempting to fire
   *     the consequence.
   */
  public synchronized void fireActivation(final Activation activation) throws ConsequenceException {
    // We do this first as if a node modifies a fact that causes a recursion
    // on an empty pattern
    // we need to make sure it re-activates
    this.workingMemory.startOperation();
    isFiringActivation = true;
    try {
      final EventSupport eventsupport = (EventSupport) this.workingMemory;

      eventsupport
          .getAgendaEventSupport()
          .fireBeforeActivationFired(activation, this.workingMemory);

      if (activation.getActivationGroupNode() != null) {
        // We know that this rule will cancel all other activations in the group
        // so lets remove the information now, before the consequence fires
        final InternalActivationGroup activationGroup =
            activation.getActivationGroupNode().getActivationGroup();
        activationGroup.removeActivation(activation);
        clearAndCancelActivationGroup(activationGroup);
      }
      activation.setQueued(false);

      try {

        this.knowledgeHelper.setActivation(activation);
        if (log.isTraceEnabled()) {
          log.trace("Fire \"{}\" \n{}", activation.getRule().getName(), activation.getTuple());
        }
        activation.getConsequence().evaluate(this.knowledgeHelper, this.workingMemory);
        this.knowledgeHelper.cancelRemainingPreviousLogicalDependencies();
        this.knowledgeHelper.reset();
      } catch (final Exception e) {
        if (this.legacyConsequenceExceptionHandler != null) {
          this.legacyConsequenceExceptionHandler.handleException(activation, this.workingMemory, e);
        } else if (this.consequenceExceptionHandler != null) {
          this.consequenceExceptionHandler.handleException(
              activation, this.workingMemory.getKnowledgeRuntime(), e);
        } else {
          throw new RuntimeException(e);
        }
      } finally {
        if (activation.getFactHandle() != null) {
          // update the Activation in the WM
          InternalFactHandle factHandle = activation.getFactHandle();
          workingMemory
              .getEntryPointNode()
              .modifyActivation(factHandle, activation.getPropagationContext(), workingMemory);
          activation.getPropagationContext().evaluateActionQueue(workingMemory);
        }
        // if the tuple contains expired events
        for (LeftTuple tuple = activation.getTuple(); tuple != null; tuple = tuple.getParent()) {
          if (tuple.getLastHandle() == null) {
            // can be null for eval, not and exists that have no right input
            continue;
          }
          if (tuple.getLastHandle().isEvent()) {
            EventFactHandle handle = (EventFactHandle) tuple.getLastHandle();
            // decrease the activation count for the event
            handle.decreaseActivationsCount();
            // handles "expire" only in stream mode.
            if (handle.isExpired()) {
              if (handle.getActivationsCount() <= 0) {
                // and if no more activations, retract the handle
                handle.getEntryPoint().retract(handle);
              }
            }
          }
        }
      }

      eventsupport.getAgendaEventSupport().fireAfterActivationFired(activation, this.workingMemory);

      unstageActivations();
    } finally {
      isFiringActivation = false;
      if (mustNotifyHalt) {
        mustNotifyHalt = false;
        notifyHalt();
      }
      this.workingMemory.endOperation();
    }
  }
  private static void readBeliefSet(
      MarshallerReaderContext context,
      TruthMaintenanceSystem tms,
      EqualityKey key,
      ProtobufMessages.BeliefSet _beliefSet)
      throws IOException, ClassNotFoundException {
    InternalFactHandle handle = (InternalFactHandle) context.handles.get(_beliefSet.getHandleId());
    for (ProtobufMessages.LogicalDependency _logicalDependency :
        _beliefSet.getLogicalDependencyList()) {
      ProtobufMessages.Activation _activation = _logicalDependency.getActivation();
      Activation activation =
          (Activation)
              context
                  .filter
                  .getTuplesCache()
                  .get(
                      PersisterHelper.createActivationKey(
                          _activation.getPackageName(),
                          _activation.getRuleName(),
                          _activation.getTuple()))
                  .getObject();

      Object object = null;
      ObjectMarshallingStrategy strategy = null;
      if (_logicalDependency.hasObjectStrategyIndex()) {
        strategy = context.usedStrategies.get(_logicalDependency.getObjectStrategyIndex());
        object =
            strategy.unmarshal(
                context.strategyContexts.get(strategy),
                context,
                _logicalDependency.getObject().toByteArray(),
                (context.ruleBase == null) ? null : context.ruleBase.getRootClassLoader());
      }

      Object value = null;
      if (_logicalDependency.hasValueStrategyIndex()) {
        strategy = context.usedStrategies.get(_logicalDependency.getValueStrategyIndex());
        value =
            strategy.unmarshal(
                context.strategyContexts.get(strategy),
                context,
                _logicalDependency.getValue().toByteArray(),
                (context.ruleBase == null) ? null : context.ruleBase.getRootClassLoader());
      }

      ObjectTypeConf typeConf =
          context
              .wm
              .getObjectTypeConfigurationRegistry()
              .getObjectTypeConf(
                  ((NamedEntryPoint) handle.getEntryPoint()).getEntryPoint(), handle.getObject());
      tms.readLogicalDependency(
          handle,
          object,
          value,
          activation,
          activation.getPropagationContext(),
          activation.getRule(),
          typeConf);
    }
  }
  private static void writeAgenda(
      MarshallerWriteContext context, ProtobufMessages.RuleData.Builder _ksb) throws IOException {
    InternalWorkingMemory wm = context.wm;
    InternalAgenda agenda = (InternalAgenda) wm.getAgenda();

    org.drools.core.marshalling.impl.ProtobufMessages.Agenda.Builder _ab =
        ProtobufMessages.Agenda.newBuilder();

    AgendaGroup[] agendaGroups =
        (AgendaGroup[])
            agenda
                .getAgendaGroupsMap()
                .values()
                .toArray(new AgendaGroup[agenda.getAgendaGroupsMap().size()]);
    Arrays.sort(agendaGroups, AgendaGroupSorter.instance);
    for (AgendaGroup ag : agendaGroups) {
      AgendaGroupQueueImpl group = (AgendaGroupQueueImpl) ag;
      org.drools.core.marshalling.impl.ProtobufMessages.Agenda.AgendaGroup.Builder _agb =
          ProtobufMessages.Agenda.AgendaGroup.newBuilder();
      _agb.setName(group.getName())
          .setIsActive(group.isActive())
          .setIsAutoDeactivate(group.isAutoDeactivate())
          .setClearedForRecency(group.getClearedForRecency())
          .setHasRuleFlowLister(group.isRuleFlowListener())
          .setActivatedForRecency(group.getActivatedForRecency());

      Map<Long, String> nodeInstances = group.getNodeInstances();
      for (Map.Entry<Long, String> entry : nodeInstances.entrySet()) {
        org.drools.core.marshalling.impl.ProtobufMessages.Agenda.AgendaGroup.NodeInstance.Builder
            _nib = ProtobufMessages.Agenda.AgendaGroup.NodeInstance.newBuilder();
        _nib.setProcessInstanceId(entry.getKey());
        _nib.setNodeInstanceId(entry.getValue());
        _agb.addNodeInstance(_nib.build());
      }

      _ab.addAgendaGroup(_agb.build());
    }

    org.drools.core.marshalling.impl.ProtobufMessages.Agenda.FocusStack.Builder _fsb =
        ProtobufMessages.Agenda.FocusStack.newBuilder();
    LinkedList<AgendaGroup> focusStack = agenda.getStackList();
    for (Iterator<AgendaGroup> it = focusStack.iterator(); it.hasNext(); ) {
      AgendaGroup group = it.next();
      _fsb.addGroupName(group.getName());
    }
    _ab.setFocusStack(_fsb.build());

    // serialize all dormant activations
    org.drools.core.util.Iterator it = ActivationIterator.iterator(wm);
    List<org.drools.core.spi.Activation> dormant = new ArrayList<org.drools.core.spi.Activation>();
    for (org.drools.core.spi.Activation item = (org.drools.core.spi.Activation) it.next();
        item != null;
        item = (org.drools.core.spi.Activation) it.next()) {
      if (!item.isQueued()) {
        dormant.add(item);
      }
    }
    Collections.sort(dormant, ActivationsSorter.INSTANCE);
    for (org.drools.core.spi.Activation activation : dormant) {
      _ab.addMatch(writeActivation(context, (AgendaItem) activation));
    }

    // serialize all network evaluator activations
    for (Activation activation : agenda.getActivations()) {
      if (activation.isRuleAgendaItem()) {
        // serialize it
        _ab.addRuleActivation(writeActivation(context, (AgendaItem) activation));
      }
    }

    _ksb.setAgenda(_ab.build());
  }