Esempio n. 1
0
  public static void writeBehaviours(WindowNode windowNode, MarshallerWriteContext outCtx)
      throws IOException {
    Behavior[] behaviors = windowNode.getBehaviors();

    WindowMemory memory = (WindowMemory) outCtx.wm.getNodeMemory(windowNode);

    Object[] behaviorContexts = (Object[]) memory.behaviorContext;

    for (int i = 0; i < behaviors.length; i++) {
      if (windowNode.getBehaviors()[i] instanceof SlidingTimeWindow) {
        outCtx.writeShort(PersisterEnums.SLIDING_TIME_WIN);
        outCtx.writeInt(i);
        writeSlidingTimeWindowBehaviour(
            (SlidingTimeWindow) windowNode.getBehaviors()[i],
            (SlidingTimeWindowContext) behaviorContexts[i],
            outCtx);
      } else if (windowNode.getBehaviors()[i] instanceof SlidingLengthWindow) {
        outCtx.writeShort(PersisterEnums.SLIDING_LENGTH_WIN);
        outCtx.writeInt(i);
        writeSlidingLengthWindowBehaviour(
            (SlidingLengthWindow) windowNode.getBehaviors()[i],
            (SlidingLengthWindowContext) behaviorContexts[i],
            outCtx);
      }
    }
    outCtx.writeShort(PersisterEnums.END);
  }
  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);
  }
Esempio n. 3
0
  public static void writeActionQueue(MarshallerWriteContext context) throws IOException {
    ReteooWorkingMemory wm = (ReteooWorkingMemory) context.wm;

    WorkingMemoryAction[] queue =
        wm.getActionQueue().toArray(new WorkingMemoryAction[wm.getActionQueue().size()]);
    for (int i = queue.length - 1; i >= 0; i--) {
      context.writeShort(PersisterEnums.WORKING_MEMORY_ACTION);
      queue[i].write(context);
    }
    context.writeShort(PersisterEnums.END);
  }
Esempio n. 4
0
  public static ContentData marshal(Object o, Environment env) {
    MarshallerWriteContext context = null;
    ContentData content = null;
    try {
      MarshallingConfigurationImpl marshallingConfigurationImpl = null;
      if (env != null) {
        marshallingConfigurationImpl =
            new MarshallingConfigurationImpl(
                (ObjectMarshallingStrategy[])
                    env.get(EnvironmentName.OBJECT_MARSHALLING_STRATEGIES),
                false,
                false);
      } else {
        marshallingConfigurationImpl =
            new MarshallingConfigurationImpl(
                new ObjectMarshallingStrategy[] {
                  new SerializablePlaceholderResolverStrategy(
                      ClassObjectMarshallingStrategyAcceptor.DEFAULT)
                },
                false,
                false);
      }
      ObjectMarshallingStrategyStore objectMarshallingStrategyStore =
          marshallingConfigurationImpl.getObjectMarshallingStrategyStore();
      ByteArrayOutputStream stream = new ByteArrayOutputStream();

      context =
          new MarshallerWriteContext(stream, null, null, null, objectMarshallingStrategyStore, env);
      Variable marshallVariable = null;
      if (o instanceof Map) {
        marshallVariable =
            ProtobufProcessMarshaller.marshallVariablesMap(context, (Map<String, Object>) o);
      } else {
        marshallVariable = ProtobufProcessMarshaller.marshallVariable(context, "results", o);
      }
      PersisterHelper.writeToStreamWithHeader(context, marshallVariable);

      context.close();

      byte[] toByteArray = stream.toByteArray();

      content = new ContentData();
      content.setContent(toByteArray);
      content.setType(o.getClass().getCanonicalName());
      content.setAccessType(AccessType.Inline);

    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return content;
  }
Esempio n. 5
0
  public static void writeTimers(Collection<TimerJobInstance> timers, MarshallerWriteContext outCtx)
      throws IOException {
    List<TimerJobInstance> sortedTimers = new ArrayList<TimerJobInstance>(timers);
    Collections.sort(
        sortedTimers,
        new Comparator<TimerJobInstance>() {
          public int compare(TimerJobInstance o1, TimerJobInstance o2) {
            return (int) (o1.getJobHandle().getId() - o2.getJobHandle().getId());
          }
        });

    for (TimerJobInstance timer : sortedTimers) {
      outCtx.writeShort(PersisterEnums.DEFAULT_TIMER);
      JobContext jctx = ((SelfRemovalJobContext) timer.getJobContext()).getJobContext();
      TimersOutputMarshaller writer = outCtx.writersByClass.get(jctx.getClass());
      writer.write(jctx, outCtx);
    }
    outCtx.writeShort(PersisterEnums.END);
  }
  private static ProtobufMessages.FactHandle writeFactHandle(
      MarshallerWriteContext context,
      ObjectMarshallingStrategyStore objectMarshallingStrategyStore,
      InternalFactHandle handle)
      throws IOException {
    ProtobufMessages.FactHandle.Builder _handle = ProtobufMessages.FactHandle.newBuilder();

    _handle.setType(getHandleType(handle));
    _handle.setId(handle.getId());
    _handle.setRecency(handle.getRecency());

    if (_handle.getType() == ProtobufMessages.FactHandle.HandleType.EVENT) {
      // is event
      EventFactHandle efh = (EventFactHandle) handle;
      _handle.setTimestamp(efh.getStartTimestamp());
      _handle.setDuration(efh.getDuration());
      _handle.setIsExpired(efh.isExpired());
      _handle.setActivationsCount(efh.getActivationsCount());
    }

    if (handle.getEqualityKey() != null
        && handle.getEqualityKey().getStatus() == EqualityKey.JUSTIFIED) {
      _handle.setIsJustified(true);
    } else {
      _handle.setIsJustified(false);
    }

    Object object = handle.getObject();

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

      Integer index = context.getStrategyIndex(strategy);
      _handle.setStrategyIndex(index.intValue());
      _handle.setObject(
          ByteString.copyFrom(
              strategy.marshal(context.strategyContext.get(strategy), context, object)));
    }

    return _handle.build();
  }
Esempio n. 7
0
  public static void writeLeftTuple(
      LeftTuple leftTuple, MarshallerWriteContext context, boolean recurse) throws IOException {
    ObjectOutputStream stream = context.stream;
    InternalRuleBase ruleBase = context.ruleBase;
    InternalWorkingMemory wm = context.wm;

    LeftTupleSink sink = leftTuple.getLeftTupleSink();

    switch (sink.getType()) {
      case NodeTypeEnums.JoinNode:
        {
          // context.out.println( "JoinNode" );
          for (LeftTuple childLeftTuple = leftTuple.getFirstChild();
              childLeftTuple != null;
              childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext()) {
            stream.writeShort(PersisterEnums.RIGHT_TUPLE);
            int childSinkId = childLeftTuple.getLeftTupleSink().getId();
            stream.writeInt(childSinkId);
            stream.writeInt(childLeftTuple.getRightParent().getFactHandle().getId());
            // context.out.println( "RightTuple int:" + childLeftTuple.getLeftTupleSink().getId() +
            // " int:" + childLeftTuple.getRightParent().getFactHandle().getId() );
            writeLeftTuple(childLeftTuple, context, recurse);
          }
          stream.writeShort(PersisterEnums.END);
          // context.out.println( "JoinNode   ---   END" );
          break;
        }
      case NodeTypeEnums.QueryRiaFixerNode:
      case NodeTypeEnums.EvalConditionNode:
        {
          // context.out.println( ".... EvalConditionNode" );
          for (LeftTuple childLeftTuple = leftTuple.getFirstChild();
              childLeftTuple != null;
              childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext()) {
            stream.writeShort(PersisterEnums.LEFT_TUPLE);
            stream.writeInt(childLeftTuple.getLeftTupleSink().getId());
            writeLeftTuple(childLeftTuple, context, recurse);
          }
          stream.writeShort(PersisterEnums.END);
          // context.out.println( "---- EvalConditionNode   ---   END" );
          break;
        }
      case NodeTypeEnums.NotNode:
      case NodeTypeEnums.ForallNotNode:
        {
          if (leftTuple.getBlocker() == null) {
            // is not blocked so has children
            stream.writeShort(PersisterEnums.LEFT_TUPLE_NOT_BLOCKED);

            for (LeftTuple childLeftTuple = leftTuple.getFirstChild();
                childLeftTuple != null;
                childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext()) {
              stream.writeShort(PersisterEnums.LEFT_TUPLE);
              stream.writeInt(childLeftTuple.getLeftTupleSink().getId());
              writeLeftTuple(childLeftTuple, context, recurse);
            }
            stream.writeShort(PersisterEnums.END);

          } else {
            stream.writeShort(PersisterEnums.LEFT_TUPLE_BLOCKED);
            stream.writeInt(leftTuple.getBlocker().getFactHandle().getId());
          }
          break;
        }
      case NodeTypeEnums.ExistsNode:
        {
          if (leftTuple.getBlocker() == null) {
            // is blocked so has children
            stream.writeShort(PersisterEnums.LEFT_TUPLE_NOT_BLOCKED);
          } else {
            stream.writeShort(PersisterEnums.LEFT_TUPLE_BLOCKED);
            stream.writeInt(leftTuple.getBlocker().getFactHandle().getId());

            for (LeftTuple childLeftTuple = leftTuple.getFirstChild();
                childLeftTuple != null;
                childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext()) {
              stream.writeShort(PersisterEnums.LEFT_TUPLE);
              stream.writeInt(childLeftTuple.getLeftTupleSink().getId());
              writeLeftTuple(childLeftTuple, context, recurse);
            }
            stream.writeShort(PersisterEnums.END);
          }
          break;
        }
      case NodeTypeEnums.AccumulateNode:
        {
          // context.out.println( ".... AccumulateNode" );
          // accumulate nodes generate new facts on-demand and need special procedures when
          // serializing to persistent storage
          AccumulateMemory memory = (AccumulateMemory) context.wm.getNodeMemory((BetaNode) sink);
          AccumulateContext accctx = (AccumulateContext) leftTuple.getObject();
          // first we serialize the generated fact handle
          writeFactHandle(
              context,
              stream,
              context.objectMarshallingStrategyStore,
              accctx.result.getFactHandle());
          // then we serialize the associated accumulation context
          stream.writeObject(accctx.context);
          // then we serialize the boolean propagated flag
          stream.writeBoolean(accctx.propagated);

          // then we serialize all the propagated tuples
          for (LeftTuple childLeftTuple = leftTuple.getFirstChild();
              childLeftTuple != null;
              childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext()) {
            if (leftTuple.getLeftTupleSink().getId() == childLeftTuple.getLeftTupleSink().getId()) {
              // this is a matching record, so, associate the right tuples
              // context.out.println( "RightTuple(match) int:" +
              // childLeftTuple.getLeftTupleSink().getId() + " int:" +
              // childLeftTuple.getRightParent().getFactHandle().getId() );
              stream.writeShort(PersisterEnums.RIGHT_TUPLE);
              stream.writeInt(childLeftTuple.getRightParent().getFactHandle().getId());
            } else {
              // this is a propagation record
              // context.out.println( "RightTuple(propagation) int:" +
              // childLeftTuple.getLeftTupleSink().getId() + " int:" +
              // childLeftTuple.getRightParent().getFactHandle().getId() );
              stream.writeShort(PersisterEnums.LEFT_TUPLE);
              int sinkId = childLeftTuple.getLeftTupleSink().getId();
              stream.writeInt(sinkId);
              writeLeftTuple(childLeftTuple, context, recurse);
            }
          }
          stream.writeShort(PersisterEnums.END);
          // context.out.println( "---- AccumulateNode   ---   END" );
          break;
        }
      case NodeTypeEnums.RightInputAdaterNode:
        {
          // context.out.println( ".... RightInputAdapterNode" );
          // RIANs generate new fact handles on-demand to wrap tuples and need special procedures
          // when serializing to persistent storage
          ObjectHashMap memory = (ObjectHashMap) context.wm.getNodeMemory((NodeMemory) sink);
          InternalFactHandle ifh = (InternalFactHandle) memory.get(leftTuple);
          // first we serialize the generated fact handle ID
          // context.out.println( "FactHandle id:"+ifh.getId() );
          stream.writeInt(ifh.getId());
          stream.writeLong(ifh.getRecency());

          writeRightTuples(ifh, context);

          stream.writeShort(PersisterEnums.END);
          // context.out.println( "---- RightInputAdapterNode   ---   END" );
          break;
        }
      case NodeTypeEnums.FromNode:
        {
          // context.out.println( ".... FromNode" );
          // FNs generate new fact handles on-demand to wrap objects and need special procedures
          // when serializing to persistent storage
          FromMemory memory = (FromMemory) context.wm.getNodeMemory((NodeMemory) sink);

          Map<Object, RightTuple> matches = (Map<Object, RightTuple>) leftTuple.getObject();
          for (RightTuple rightTuples : matches.values()) {
            // first we serialize the generated fact handle ID
            stream.writeShort(PersisterEnums.FACT_HANDLE);
            writeFactHandle(
                context,
                stream,
                context.objectMarshallingStrategyStore,
                rightTuples.getFactHandle());
            writeRightTuples(rightTuples.getFactHandle(), context);
          }
          stream.writeShort(PersisterEnums.END);
          for (LeftTuple childLeftTuple = leftTuple.getFirstChild();
              childLeftTuple != null;
              childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext()) {
            stream.writeShort(PersisterEnums.RIGHT_TUPLE);
            stream.writeInt(childLeftTuple.getLeftTupleSink().getId());
            stream.writeInt(childLeftTuple.getRightParent().getFactHandle().getId());
            // context.out.println( "RightTuple int:" + childLeftTuple.getLeftTupleSink().getId() +
            // " int:" + childLeftTuple.getRightParent().getFactHandle().getId() );
            writeLeftTuple(childLeftTuple, context, recurse);
          }
          stream.writeShort(PersisterEnums.END);
          // context.out.println( "---- FromNode   ---   END" );
          break;
        }
      case NodeTypeEnums.UnificationNode:
        {
          // context.out.println( ".... UnificationNode" );

          QueryElementNode node = (QueryElementNode) sink;
          boolean isOpen = node.isOpenQuery();

          context.writeBoolean(isOpen);
          if (isOpen) {
            InternalFactHandle factHandle = (InternalFactHandle) leftTuple.getObject();
            DroolsQuery query = (DroolsQuery) factHandle.getObject();

            // context.out.println( "factHandle:" +  factHandle );

            factHandle.setObject(null);
            writeFactHandle(context, stream, context.objectMarshallingStrategyStore, 0, factHandle);
            factHandle.setObject(query);
            writeLeftTuples(context, new InternalFactHandle[] {factHandle});
          } else {
            for (LeftTuple childLeftTuple = leftTuple.getFirstChild();
                childLeftTuple != null;
                childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext()) {
              stream.writeShort(PersisterEnums.LEFT_TUPLE);
              stream.writeInt(childLeftTuple.getLeftTupleSink().getId());
              InternalFactHandle factHandle = childLeftTuple.getLastHandle();
              writeFactHandle(
                  context, stream, context.objectMarshallingStrategyStore, 1, factHandle);
              writeLeftTuple(childLeftTuple, context, recurse);
            }
            stream.writeShort(PersisterEnums.END);
          }
          // context.out.println( "---- EvalConditionNode   ---   END" );
          break;
        }
      case NodeTypeEnums.RuleTerminalNode:
        {
          // context.out.println( "RuleTerminalNode" );
          int pos = context.terminalTupleMap.size();
          context.terminalTupleMap.put(leftTuple, pos);
          break;
        }
      case NodeTypeEnums.QueryTerminalNode:
        {
          // context.out.println( ".... QueryTerminalNode" );
          //                LeftTuple entry = leftTuple;
          //
          //                // find the DroolsQuery object
          //                while ( entry.getParent() != null ) {
          //                    entry = entry.getParent();
          //                }
          //
          //                // Now output all the child tuples in the caller network
          //                DroolsQuery query = (DroolsQuery) entry.getLastHandle().getObject();
          //                if ( query.getQueryResultCollector() instanceof
          // UnificationNodeViewChangedEventListener ) {
          //                    context.writeBoolean( true );
          //                    UnificationNodeViewChangedEventListener collector =
          // (UnificationNodeViewChangedEventListener) query.getQueryResultCollector();
          //                    leftTuple = collector.getLeftTuple();
          //
          context.writeBoolean(true);
          RightTuple rightTuple = (RightTuple) leftTuple.getObject();
          // context.out.println( "rightTuple:" +  rightTuple.getFactHandle() );
          writeFactHandle(
              context,
              stream,
              context.objectMarshallingStrategyStore,
              1,
              rightTuple.getFactHandle());

          for (LeftTuple childLeftTuple = rightTuple.firstChild;
              childLeftTuple != null;
              childLeftTuple = (LeftTuple) childLeftTuple.getRightParentNext()) {
            stream.writeShort(PersisterEnums.LEFT_TUPLE);
            stream.writeInt(childLeftTuple.getLeftTupleSink().getId());
            writeLeftTuple(childLeftTuple, context, recurse);
          }

          //                    for ( LeftTuple childLeftTuple = leftTuple.getFirstChild();
          // childLeftTuple != null; childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext()
          // ) {
          //                        stream.writeShort( PersisterEnums.LEFT_TUPLE );
          //                        stream.writeInt( childLeftTuple.getLeftTupleSink().getId() );
          //                        writeFactHandle( context,
          //                                         stream,
          //                                         context.objectMarshallingStrategyStore,
          //                                         1,
          //                                         childLeftTuple.getLastHandle() );
          //                        writeLeftTuple( childLeftTuple,
          //                                        context,
          //                                        recurse );
          //                    }
          //                } else {
          //                    context.writeBoolean( false );
          //                }
          stream.writeShort(PersisterEnums.END);
          // context.out.println( "---- QueryTerminalNode   ---   END" );
          break;
        }
    }
  }
Esempio n. 8
0
  public static void writeAgenda(MarshallerWriteContext context) throws IOException {
    InternalWorkingMemory wm = context.wm;
    DefaultAgenda agenda = (DefaultAgenda) wm.getAgenda();

    context.writeInt(agenda.getDormantActivations());
    context.writeInt(agenda.getActiveActivations());

    Map<String, ActivationGroup> activationGroups = agenda.getActivationGroupsMap();

    AgendaGroup[] agendaGroups =
        (AgendaGroup[])
            agenda
                .getAgendaGroupsMap()
                .values()
                .toArray(new AgendaGroup[agenda.getAgendaGroupsMap().size()]);
    Arrays.sort(agendaGroups, AgendaGroupSorter.instance);

    for (AgendaGroup group : agendaGroups) {
      context.writeShort(PersisterEnums.AGENDA_GROUP);
      context.writeUTF(group.getName());
      context.writeBoolean(group.isActive());
    }
    context.writeShort(PersisterEnums.END);

    LinkedList<AgendaGroup> focusStack = agenda.getStackList();
    for (Iterator<AgendaGroup> it = focusStack.iterator(); it.hasNext(); ) {
      AgendaGroup group = it.next();
      context.writeShort(PersisterEnums.AGENDA_GROUP);
      context.writeUTF(group.getName());
    }
    context.writeShort(PersisterEnums.END);

    RuleFlowGroupImpl[] ruleFlowGroups =
        (RuleFlowGroupImpl[])
            agenda
                .getRuleFlowGroupsMap()
                .values()
                .toArray(new RuleFlowGroupImpl[agenda.getRuleFlowGroupsMap().size()]);
    Arrays.sort(ruleFlowGroups, RuleFlowGroupSorter.instance);

    for (RuleFlowGroupImpl group : ruleFlowGroups) {
      context.writeShort(PersisterEnums.RULE_FLOW_GROUP);
      // group.write( context );
      context.writeUTF(group.getName());
      context.writeBoolean(group.isActive());
      context.writeBoolean(group.isAutoDeactivate());
      Map<Long, String> nodeInstances = group.getNodeInstances();
      context.writeInt(nodeInstances.size());
      for (Map.Entry<Long, String> entry : nodeInstances.entrySet()) {
        context.writeLong(entry.getKey());
        context.writeUTF(entry.getValue());
      }
    }
    context.writeShort(PersisterEnums.END);
  }
Esempio n. 9
0
  public static void writeTrigger(Trigger trigger, MarshallerWriteContext outCtx)
      throws IOException {
    if (trigger instanceof CronTrigger) {
      outCtx.writeShort(PersisterEnums.CRON_TRIGGER);

      CronTrigger cronTrigger = (CronTrigger) trigger;
      outCtx.writeLong(cronTrigger.getStartTime().getTime());
      if (cronTrigger.getEndTime() != null) {
        outCtx.writeBoolean(true);
        outCtx.writeLong(cronTrigger.getEndTime().getTime());
      } else {
        outCtx.writeBoolean(false);
      }
      outCtx.writeInt(cronTrigger.getRepeatLimit());
      outCtx.writeInt(cronTrigger.getRepeatCount());
      outCtx.writeUTF(cronTrigger.getCronEx().getCronExpression());
      if (cronTrigger.getNextFireTime() != null) {
        outCtx.writeBoolean(true);
        outCtx.writeLong(cronTrigger.getNextFireTime().getTime());
      } else {
        outCtx.writeBoolean(false);
      }
      outCtx.writeObject(cronTrigger.getCalendarNames());
    } else if (trigger instanceof IntervalTrigger) {
      outCtx.writeShort(PersisterEnums.INT_TRIGGER);

      IntervalTrigger intTrigger = (IntervalTrigger) trigger;
      outCtx.writeLong(intTrigger.getStartTime().getTime());
      if (intTrigger.getEndTime() != null) {
        outCtx.writeBoolean(true);
        outCtx.writeLong(intTrigger.getEndTime().getTime());
      } else {
        outCtx.writeBoolean(false);
      }
      outCtx.writeInt(intTrigger.getRepeatLimit());
      outCtx.writeInt(intTrigger.getRepeatCount());
      if (intTrigger.getNextFireTime() != null) {
        outCtx.writeBoolean(true);
        outCtx.writeLong(intTrigger.getNextFireTime().getTime());
      } else {
        outCtx.writeBoolean(false);
      }
      outCtx.writeLong(intTrigger.getPeriod());
      outCtx.writeObject(intTrigger.getCalendarNames());
    } else if (trigger instanceof PointInTimeTrigger) {
      outCtx.writeShort(PersisterEnums.POINT_IN_TIME_TRIGGER);

      PointInTimeTrigger pinTrigger = (PointInTimeTrigger) trigger;

      outCtx.writeLong(pinTrigger.hasNextFireTime().getTime());
    }

    //        else if ( trigger instanceof DelayedTrigger ) {
    //
    //        } else if ( trigger instanceof PointInTimeTrigger ) {
    //
    //        } else if ( trigger instanceof CompositeMaxDurationTimer ) {
    //
    //        }
  }
Esempio n. 10
0
  public static void writeSession(MarshallerWriteContext context) throws IOException {
    // context.out.println( "... write session");
    ReteooWorkingMemory wm = (ReteooWorkingMemory) context.wm;
    wm.getAgenda().unstageActivations();

    final boolean multithread = wm.isPartitionManagersActive();
    // is multi-thread active?
    if (multithread) {
      context.writeBoolean(true);
      wm.stopPartitionManagers();
    } else {
      context.writeBoolean(false);
    }

    long time = 0;
    if (context.wm.getTimerService() instanceof PseudoClockScheduler) {
      time = context.clockTime;
    }
    context.writeLong(time);

    context.writeInt(wm.getFactHandleFactory().getId());
    context.writeLong(wm.getFactHandleFactory().getRecency());
    //// context.out.println( "FactHandleFactory int:" + wm.getFactHandleFactory().getId() + "
    // long:" + wm.getFactHandleFactory().getRecency() );

    context.writeLong(wm.getPropagationIdCounter());
    // context.out.println( "PropagationCounter long:" + wm.getPropagationIdCounter() );

    InternalFactHandle handle = context.wm.getInitialFactHandle();
    context.writeInt(handle.getId());
    context.writeLong(handle.getRecency());
    // context.out.println( "InitialFact int:" + handle.getId() + " long:" + handle.getRecency() );

    writeAgenda(context);

    writeInitialFactHandleRightTuples(context);
    for (WorkingMemoryEntryPoint wmep : wm.getEntryPoints().values()) {
      context.stream.writeShort(PersisterEnums.ENTRY_POINT);
      context.stream.writeUTF(wmep.getEntryPointId());
      writeFactHandles(context, ((NamedEntryPoint) wmep).getObjectStore());
    }
    context.stream.writeShort(PersisterEnums.END);
    writeInitialFactHandleLeftTuples(context);

    writePropagationContexts(context);

    writeActivations(context);

    writeActionQueue(context);

    writeTruthMaintenanceSystem(context);

    if (context.marshalProcessInstances && processMarshaller != null) {
      processMarshaller.writeProcessInstances(context);
    } else {
      context.stream.writeShort(PersisterEnums.END);
    }

    if (context.marshalWorkItems && processMarshaller != null) {
      processMarshaller.writeWorkItems(context);
    } else {
      context.stream.writeShort(PersisterEnums.END);
    }

    if (processMarshaller != null) {
      // this now just assigns the writer, it will not write out any timer information
      processMarshaller.writeProcessTimers(context);
    } else {
      context.stream.writeShort(PersisterEnums.END);
    }

    // Only works for JpaJDKTimerService
    writeTimers(context.wm.getTimerService().getTimerJobInstances(), context);

    if (multithread) {
      wm.startPartitionManagers();
    }

    // context.out.println( "--- write session --- END");
  }
  private static ProtobufMessages.KnowledgeSession serializeSession(MarshallerWriteContext context)
      throws IOException {
    ReteooWorkingMemory wm = (ReteooWorkingMemory) context.wm;
    wm.getAgenda().unstageActivations();

    ProtobufMessages.RuleData.Builder _ruleData = ProtobufMessages.RuleData.newBuilder();

    final boolean multithread = wm.isPartitionManagersActive();
    if (multithread) {
      wm.stopPartitionManagers();
    }

    long time = 0;
    if (context.wm.getTimerService() instanceof PseudoClockScheduler) {
      time = context.clockTime;
    }
    _ruleData.setLastId(wm.getFactHandleFactory().getId());
    _ruleData.setLastRecency(wm.getFactHandleFactory().getRecency());

    InternalFactHandle handle = context.wm.getInitialFactHandle();
    ProtobufMessages.FactHandle _ifh =
        ProtobufMessages.FactHandle.newBuilder()
            .setType(ProtobufMessages.FactHandle.HandleType.INITIAL_FACT)
            .setId(handle.getId())
            .setRecency(handle.getRecency())
            .build();
    _ruleData.setInitialFact(_ifh);

    writeAgenda(context, _ruleData);

    writeNodeMemories(context, _ruleData);

    for (WorkingMemoryEntryPoint wmep : wm.getEntryPoints().values()) {
      org.drools.marshalling.impl.ProtobufMessages.EntryPoint.Builder _epb =
          ProtobufMessages.EntryPoint.newBuilder();
      _epb.setEntryPointId(wmep.getEntryPointId());
      writeFactHandles(context, _epb, ((NamedEntryPoint) wmep).getObjectStore());
      _ruleData.addEntryPoint(_epb.build());
    }

    writeActionQueue(context, _ruleData);

    writeTruthMaintenanceSystem(context, _ruleData);

    ProtobufMessages.KnowledgeSession.Builder _session =
        ProtobufMessages.KnowledgeSession.newBuilder()
            .setMultithread(multithread)
            .setTime(time)
            .setRuleData(_ruleData.build());

    if (processMarshaller != null) {
      Builder _pdata = ProtobufMessages.ProcessData.newBuilder();
      if (context.marshalProcessInstances) {
        context.parameterObject = _pdata;
        processMarshaller.writeProcessInstances(context);
      }

      if (context.marshalWorkItems) {
        context.parameterObject = _pdata;
        processMarshaller.writeWorkItems(context);
      }

      // this now just assigns the writer, it will not write out any timer information
      context.parameterObject = _pdata;
      processMarshaller.writeProcessTimers(context);

      _session.setProcessData(_pdata.build());
    }

    Timers _timers = writeTimers(context.wm.getTimerService().getTimerJobInstances(), context);
    if (_timers != null) {
      _session.setTimers(_timers);
    }

    if (multithread) {
      wm.startPartitionManagers();
    }

    return _session.build();
  }
  private static ProtobufMessages.KnowledgeSession serializeSession(MarshallerWriteContext context)
      throws IOException {
    StatefulKnowledgeSessionImpl wm = (StatefulKnowledgeSessionImpl) context.wm;

    try {
      wm.getLock().lock();
      for (WorkingMemoryEntryPoint ep : wm.getWorkingMemoryEntryPoints().values()) {
        if (ep instanceof NamedEntryPoint) {
          ((NamedEntryPoint) ep).lock();
        }
      }

      ((InternalAgenda) wm.getAgenda()).unstageActivations();

      evaluateRuleActivations(wm);

      ProtobufMessages.RuleData.Builder _ruleData = ProtobufMessages.RuleData.newBuilder();

      long time = 0;
      if (context.wm.getTimerService() instanceof PseudoClockScheduler) {
        time = context.clockTime;
      }
      _ruleData.setLastId(wm.getFactHandleFactory().getId());
      _ruleData.setLastRecency(wm.getFactHandleFactory().getRecency());

      InternalFactHandle handle = context.wm.getInitialFactHandle();
      if (handle != null) {
        // can be null for RETE, if fireAllRules has not yet been called
        ProtobufMessages.FactHandle _ifh =
            ProtobufMessages.FactHandle.newBuilder()
                .setType(ProtobufMessages.FactHandle.HandleType.INITIAL_FACT)
                .setId(handle.getId())
                .setRecency(handle.getRecency())
                .build();
        _ruleData.setInitialFact(_ifh);
      }

      writeAgenda(context, _ruleData);

      writeNodeMemories(context, _ruleData);

      for (EntryPoint wmep : wm.getWorkingMemoryEntryPoints().values()) {
        org.drools.core.marshalling.impl.ProtobufMessages.EntryPoint.Builder _epb =
            ProtobufMessages.EntryPoint.newBuilder();
        _epb.setEntryPointId(wmep.getEntryPointId());

        writeObjectTypeConfiguration(
            context,
            ((InternalWorkingMemoryEntryPoint) wmep).getObjectTypeConfigurationRegistry(),
            _epb);

        writeFactHandles(context, _epb, ((NamedEntryPoint) wmep).getObjectStore());

        writeTruthMaintenanceSystem(context, wmep, _epb);

        _ruleData.addEntryPoint(_epb.build());
      }

      writeActionQueue(context, _ruleData);

      ProtobufMessages.KnowledgeSession.Builder _session =
          ProtobufMessages.KnowledgeSession.newBuilder()
              .setMultithread(false)
              .setTime(time)
              .setRuleData(_ruleData.build());

      if (processMarshaller != null) {
        Builder _pdata = ProtobufMessages.ProcessData.newBuilder();
        if (context.marshalProcessInstances) {
          context.parameterObject = _pdata;
          processMarshaller.writeProcessInstances(context);
        }

        if (context.marshalWorkItems) {
          context.parameterObject = _pdata;
          processMarshaller.writeWorkItems(context);
        }

        // this now just assigns the writer, it will not write out any timer information
        context.parameterObject = _pdata;
        processMarshaller.writeProcessTimers(context);

        _session.setProcessData(_pdata.build());
      }

      Timers _timers =
          writeTimers(
              context.wm.getTimerService().getTimerJobInstances(context.wm.getId()), context);
      if (_timers != null) {
        _session.setTimers(_timers);
      }

      return _session.build();
    } finally {
      for (WorkingMemoryEntryPoint ep : wm.getWorkingMemoryEntryPoints().values()) {
        if (ep instanceof NamedEntryPoint) {
          ((NamedEntryPoint) ep).unlock();
        }
      }
      wm.getLock().unlock();
    }
  }