示例#1
0
  public void updateSink(
      final ObjectSink sink,
      final PropagationContext context,
      final InternalWorkingMemory workingMemory) {
    // @todo
    // JBRULES-612: the cache MUST be invalidated when a new node type is added to the network, so
    // iterate and reset all caches.
    final ObjectTypeNode node = (ObjectTypeNode) sink;

    final ObjectType newObjectType = node.getObjectType();

    InternalWorkingMemoryEntryPoint wmEntryPoint =
        (InternalWorkingMemoryEntryPoint)
            workingMemory.getWorkingMemoryEntryPoint(this.entryPoint.getEntryPointId());

    for (ObjectTypeConf objectTypeConf :
        wmEntryPoint.getObjectTypeConfigurationRegistry().values()) {
      if (newObjectType.isAssignableFrom(
          objectTypeConf.getConcreteObjectTypeNode().getObjectType())) {
        objectTypeConf.resetCache();
        ObjectTypeNode sourceNode = objectTypeConf.getConcreteObjectTypeNode();
        Iterator it =
            ((ObjectTypeNodeMemory) workingMemory.getNodeMemory(sourceNode)).memory.iterator();
        for (ObjectEntry entry = (ObjectEntry) it.next();
            entry != null;
            entry = (ObjectEntry) it.next()) {
          sink.assertObject((InternalFactHandle) entry.getValue(), context, workingMemory);
        }
      }
    }
  }
示例#2
0
  public static void writeInitialFactHandleRightTuples(MarshallerWriteContext context)
      throws IOException {
    ObjectOutputStream stream = context.stream;
    InternalRuleBase ruleBase = context.ruleBase;

    ObjectTypeNode initialFactNode =
        ruleBase
            .getRete()
            .getEntryPointNode(EntryPoint.DEFAULT)
            .getObjectTypeNodes()
            .get(ClassObjectType.InitialFact_ObjectType);

    // do we write the fact to the objecttypenode memory
    if (initialFactNode != null) {
      ObjectHashSet initialFactMemory = (ObjectHashSet) context.wm.getNodeMemory(initialFactNode);
      if (initialFactMemory != null && !initialFactMemory.isEmpty()) {
        // context.out.println( "InitialFactMemory true int:" + initialFactNode.getId() );
        stream.writeBoolean(true);
        stream.writeInt(initialFactNode.getId());

        // context.out.println( "InitialFact RightTuples" );
        writeRightTuples(context.wm.getInitialFactHandle(), context);
      } else {
        // context.out.println( "InitialFactMemory false " );
        stream.writeBoolean(false);
      }
    } else {
      // context.out.println( "InitialFactMemory false " );
      stream.writeBoolean(false);
    }
  }
示例#3
0
  public static ObjectTypeNode attachObjectTypeNode(BuildContext context, ObjectType objectType) {
    final InternalRuleBase ruleBase = context.getRuleBase();
    ruleBase.readLock();
    try {
      InternalWorkingMemory[] wms = context.getWorkingMemories();

      EntryPointNode epn = ruleBase.getRete().getEntryPointNode(context.getCurrentEntryPoint());
      if (epn == null) {
        epn = new EntryPointNode(context.getNextId(), ruleBase.getRete(), context);
        if (wms.length > 0) {
          epn.attach(wms);
        } else {
          epn.attach();
        }
      }

      ObjectTypeNode otn = new ObjectTypeNode(context.getNextId(), epn, objectType, context);

      long expirationOffset = getExpiratioOffsetForType(context, objectType);
      otn.setExpirationOffset(expirationOffset);

      if (wms.length > 0) {
        otn.attach(wms);
      } else {
        otn.attach();
      }

      return otn;
    } finally {
      ruleBase.readUnlock();
    }
  }
  @Test
  public void testSingleSharedEmptyLhs() throws Exception {
    KnowledgeBase kbase = buildKnowledgeBase(" ", " ");

    ReteooWorkingMemoryInterface wm =
        ((StatefulKnowledgeSessionImpl) kbase.newStatefulKnowledgeSession()).session;

    ObjectTypeNode aotn = getObjectTypeNode(kbase, InitialFactImpl.class);

    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn1 = (RuleTerminalNode) liaNode.getSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn2 = (RuleTerminalNode) liaNode.getSinkPropagator().getSinks()[1];

    wm.insert(new A());

    // LiaNode  is in it's own segment
    LiaNodeMemory liaMem = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    SegmentMemory smem = liaMem.getSegmentMemory();
    assertEquals(liaNode, smem.getRootNode());
    assertEquals(liaNode, smem.getTipNode());

    // each RTN is in it's own segment
    SegmentMemory rtnSmem1 = smem.getFirst();
    assertEquals(rtn1, rtnSmem1.getRootNode());
    assertEquals(rtn1, rtnSmem1.getTipNode());

    SegmentMemory rtnSmem2 = rtnSmem1.getNext();
    assertEquals(rtn2, rtnSmem2.getRootNode());
    assertEquals(rtn2, rtnSmem2.getTipNode());
  }
 public ObjectTypeNode getObjectTypeNode(KnowledgeBase kbase, Class<?> nodeClass) {
   List<ObjectTypeNode> nodes =
       ((InternalRuleBase) ((KnowledgeBaseImpl) kbase).ruleBase).getRete().getObjectTypeNodes();
   for (ObjectTypeNode n : nodes) {
     if (((ClassObjectType) n.getObjectType()).getClassType() == nodeClass) {
       return n;
     }
   }
   return null;
 }
  @Test
  public void tesShareInSubnetwork() throws Exception {
    KnowledgeBase kbase =
        buildKnowledgeBase("   A() \n", "   A() B() C() \n", "   A()  not ( B() and C() ) \n");

    ReteooWorkingMemoryInterface wm =
        ((StatefulKnowledgeSessionImpl) kbase.newStatefulKnowledgeSession()).session;

    ObjectTypeNode aotn = getObjectTypeNode(kbase, A.class);

    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn1 = (RuleTerminalNode) liaNode.getSinkPropagator().getSinks()[0];

    JoinNode bNode = (JoinNode) liaNode.getSinkPropagator().getSinks()[1];
    JoinNode cNode = (JoinNode) bNode.getSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn2 = (RuleTerminalNode) cNode.getSinkPropagator().getSinks()[0];
    RightInputAdapterNode riaNode = (RightInputAdapterNode) cNode.getSinkPropagator().getSinks()[1];

    NotNode notNode = (NotNode) liaNode.getSinkPropagator().getSinks()[2];
    RuleTerminalNode rtn3 = (RuleTerminalNode) notNode.getSinkPropagator().getSinks()[0];

    wm.insert(new A());
    wm.insert(new B());
    wm.insert(new C());

    // LiaNode  is in it's own segment
    LiaNodeMemory liaMem = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    SegmentMemory smem = liaMem.getSegmentMemory();
    assertEquals(liaNode, smem.getRootNode());
    assertEquals(liaNode, smem.getTipNode());

    SegmentMemory rtnSmem1 = smem.getFirst();
    assertEquals(rtn1, rtnSmem1.getRootNode());
    assertEquals(rtn1, rtnSmem1.getTipNode());

    SegmentMemory bSmem = rtnSmem1.getNext();
    assertEquals(bNode, bSmem.getRootNode());
    assertEquals(cNode, bSmem.getTipNode());

    assertNull(bSmem.getFirst()); // segment is not initialized yet

    wm.fireAllRules();

    SegmentMemory rtn2Smem = bSmem.getFirst();
    assertEquals(rtn2, rtn2Smem.getRootNode());
    assertEquals(rtn2, rtn2Smem.getTipNode());

    SegmentMemory riaSmem = rtn2Smem.getNext();
    assertEquals(riaNode, riaSmem.getRootNode());
    assertEquals(riaNode, riaSmem.getTipNode());

    SegmentMemory notSmem = bSmem.getNext();
    assertEquals(notNode, notSmem.getRootNode());
    assertEquals(rtn3, notSmem.getTipNode());
  }
  @Test
  public void testMultiSharedPattern() throws Exception {
    KnowledgeBase kbase = buildKnowledgeBase("   A() \n", "   A() B() \n", "   A() B() C() \n");

    ReteooWorkingMemoryInterface wm =
        ((StatefulKnowledgeSessionImpl) kbase.newStatefulKnowledgeSession()).session;

    ObjectTypeNode aotn = getObjectTypeNode(kbase, A.class);

    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn1 = (RuleTerminalNode) liaNode.getSinkPropagator().getSinks()[0];
    JoinNode bNode = (JoinNode) liaNode.getSinkPropagator().getSinks()[1];
    RuleTerminalNode rtn2 = (RuleTerminalNode) bNode.getSinkPropagator().getSinks()[0];

    JoinNode cNode = (JoinNode) bNode.getSinkPropagator().getSinks()[1];
    RuleTerminalNode rtn3 = (RuleTerminalNode) cNode.getSinkPropagator().getSinks()[0];

    wm.insert(new A());
    wm.insert(new B());
    wm.insert(new C());

    // LiaNode  is in it's own segment
    LiaNodeMemory liaMem = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    SegmentMemory smem = liaMem.getSegmentMemory();
    assertEquals(liaNode, smem.getRootNode());
    assertEquals(liaNode, smem.getTipNode());

    SegmentMemory rtnSmem1 = smem.getFirst();
    assertEquals(rtn1, rtnSmem1.getRootNode());
    assertEquals(rtn1, rtnSmem1.getTipNode());

    SegmentMemory bSmem = rtnSmem1.getNext();
    assertEquals(bNode, bSmem.getRootNode());
    assertEquals(bNode, bSmem.getTipNode());

    // child segment is not yet initialised, so null
    assertNull(bSmem.getFirst());

    // there is no next
    assertNull(bSmem.getNext());

    wm.fireAllRules(); // child segments should now be initialised

    SegmentMemory rtnSmem2 = bSmem.getFirst();
    assertEquals(rtn2, rtnSmem2.getRootNode());
    assertEquals(rtn2, rtnSmem2.getTipNode());

    SegmentMemory cSmem = rtnSmem2.getNext();
    assertEquals(cNode, cSmem.getRootNode());
    assertEquals(rtn3, cSmem.getTipNode()); // note rtn3 is in the same segment as C
  }
 /**
  * Constructus a LeftInputAdapterNode with a unique id that receives <code>FactHandle</code> from
  * a parent <code>ObjectSource</code> and adds it to a given pattern in the resulting Tuples.
  *
  * @param id The unique id of this node in the current Rete network
  * @param source The parent node, where Facts are propagated from
  */
 public LeftInputAdapterNode(final int id, final ObjectSource source, final BuildContext context) {
   super(
       id,
       context.getPartitionId(),
       context.getRuleBase().getConfiguration().isMultithreadEvaluation());
   this.objectSource = source;
   this.leftTupleMemoryEnabled = context.isTupleMemoryEnabled();
   ObjectSource current = source;
   while (!(current instanceof ObjectTypeNode)) {
     current = current.getParentObjectSource();
   }
   ObjectTypeNode otn = (ObjectTypeNode) current;
   rootQueryNode = ClassObjectType.DroolsQuery_ObjectType.isAssignableFrom(otn.getObjectType());
 }
示例#9
0
  @Test
  public void testEvalDetectionInBetaNode() {
    // Tests evals are generated and executed with Java dialect

    String drl = "";
    drl += "package org.test\n";
    drl += "import org.drools.Person\n";
    drl += "global java.util.List list\n";
    drl += "rule test1\n";
    drl += "when\n";
    drl += "   $s  : String()\n";
    drl += "   $p1 : Person( eval( name \n != $s ), name == ( new String($s+\"xxx\") ) )\n";
    drl += "then\n";
    drl += "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newReaderResource(new StringReader(drl)), ResourceType.DRL);
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }
    assertFalse(kbuilder.hasErrors());

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    List<ObjectTypeNode> nodes =
        ((InternalRuleBase) ((KnowledgeBaseImpl) kbase).ruleBase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for (ObjectTypeNode n : nodes) {
      if (((ClassObjectType) n.getObjectType()).getClassType() == Person.class) {
        node = n;
        break;
      }
    }

    BetaNode betaanode = (BetaNode) node.getSinkPropagator().getSinks()[0];
    BetaNodeFieldConstraint[] constraint = (BetaNodeFieldConstraint[]) betaanode.getConstraints();
    PredicateConstraint c = (PredicateConstraint) constraint[0];
    assertTrue(c.getPredicateExpression() instanceof PredicateExpression);
    assertTrue(c.getPredicateExpression() instanceof CompiledInvoker);
    assertTrue(!(c.getPredicateExpression() instanceof MVELPredicateExpression));

    ReturnValueRestriction r =
        (ReturnValueRestriction) ((VariableConstraint) constraint[1]).getRestriction();
    assertTrue(r.getExpression() instanceof ReturnValueExpression);
    assertTrue(r.getExpression() instanceof CompiledInvoker);
    assertTrue(!(r.getExpression() instanceof MVELReturnValueExpression));
  }
示例#10
0
  @Test
  public void testEvalDetectionInAlphaNode() {
    // Tests evals are generated and executed with Java dialect
    String drl = "";
    drl += "package org.test\n";
    drl += "import org.drools.Person\n";
    drl += "global java.util.List list\n";
    drl += "rule test1\n";
    drl += "when\n";
    drl += "   $p1 : Person( eval( name \n != null ), name == ( new String(\"xxx\") ) )\n";
    drl += "then\n";
    drl += "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newReaderResource(new StringReader(drl)), ResourceType.DRL);
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }
    assertFalse(kbuilder.hasErrors());

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    List<ObjectTypeNode> nodes =
        ((InternalRuleBase) ((KnowledgeBaseImpl) kbase).ruleBase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for (ObjectTypeNode n : nodes) {
      if (((ClassObjectType) n.getObjectType()).getClassType() == Person.class) {
        node = n;
        break;
      }
    }

    AlphaNode alphanode = (AlphaNode) node.getSinkPropagator().getSinks()[0];
    PredicateConstraint c = (PredicateConstraint) alphanode.getConstraint();
    assertTrue(c.getPredicateExpression() instanceof PredicateExpression);
    assertTrue(c.getPredicateExpression() instanceof CompiledInvoker);
    assertTrue(!(c.getPredicateExpression() instanceof MVELPredicateExpression));

    alphanode = (AlphaNode) alphanode.getSinkPropagator().getSinks()[0];
    AlphaNodeFieldConstraint constraint = alphanode.getConstraint();

    if (constraint instanceof LiteralConstraint) {
      FieldValue fieldVal = ((LiteralConstraint) constraint).getField();
      assertEquals("xxx", fieldVal.getValue());
    }
  }
示例#11
0
 public String getNameSufix() {
   char[] name = node.getEntryPoint().getEntryPointId().toCharArray();
   for (int i = 0; i < name.length; i++) {
     if (!Character.isLetter(name[i]) && name[i] != ' ') {
       name[i] = '_';
     }
   }
   return new String(name);
 }
示例#12
0
 public static Class<?> getNodeClass(ObjectTypeNode objectTypeNode) {
   if (objectTypeNode == null) {
     return null;
   }
   ObjectType objectType = objectTypeNode.getObjectType();
   return objectType != null && objectType instanceof ClassObjectType
       ? ((ClassObjectType) objectType).getClassType()
       : null;
 }
  @Test
  public void testSinglePattern() throws Exception {
    KnowledgeBase kbase = buildKnowledgeBase("   A() \n");

    ReteooWorkingMemoryInterface wm =
        ((StatefulKnowledgeSessionImpl) kbase.newStatefulKnowledgeSession()).session;

    ObjectTypeNode aotn = getObjectTypeNode(kbase, A.class);

    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getSinkPropagator().getSinks()[0];
    RuleTerminalNode rtn = (RuleTerminalNode) liaNode.getSinkPropagator().getSinks()[0];

    wm.insert(new A());

    // LiaNode and Rule are in same segment
    LiaNodeMemory liaMem = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    SegmentMemory smem = liaMem.getSegmentMemory();
    assertEquals(liaNode, smem.getRootNode());
    assertEquals(rtn, smem.getTipNode());
    assertNull(smem.getNext());
    assertNull(smem.getFirst());
  }
  @Test
  public void testSubnetworkNoSharing() throws Exception {
    KnowledgeBase kbase = buildKnowledgeBase(" A()  not ( B() and C() ) \n");

    ReteooWorkingMemoryInterface wm =
        ((StatefulKnowledgeSessionImpl) kbase.newStatefulKnowledgeSession()).session;

    ObjectTypeNode aotn = getObjectTypeNode(kbase, A.class);

    LeftInputAdapterNode liaNode = (LeftInputAdapterNode) aotn.getSinkPropagator().getSinks()[0];

    JoinNode bNode = (JoinNode) liaNode.getSinkPropagator().getSinks()[0];
    JoinNode cNode = (JoinNode) bNode.getSinkPropagator().getSinks()[0];
    RightInputAdapterNode riaNode = (RightInputAdapterNode) cNode.getSinkPropagator().getSinks()[0];

    NotNode notNode = (NotNode) liaNode.getSinkPropagator().getSinks()[1];
    RuleTerminalNode rtn1 = (RuleTerminalNode) notNode.getSinkPropagator().getSinks()[0];

    wm.insert(new A());
    wm.insert(new B());
    wm.insert(new C());

    // LiaNode and Rule are in same segment
    LiaNodeMemory liaMem = (LiaNodeMemory) wm.getNodeMemory(liaNode);
    SegmentMemory smem = liaMem.getSegmentMemory();
    assertEquals(liaNode, smem.getRootNode());
    assertEquals(rtn1, smem.getTipNode());
    assertNull(smem.getNext());
    assertNull(smem.getFirst());

    SegmentMemory bSmem =
        wm.getNodeMemory(bNode).getSegmentMemory(); // it's nested inside of smem, so lookup from wm
    assertEquals(bNode, bSmem.getRootNode());
    assertEquals(riaNode, bSmem.getTipNode());

    BetaMemory bm = (BetaMemory) wm.getNodeMemory(notNode);
    assertEquals(bSmem, bm.getSubnetworkSegmentMemory()); // check subnetwork ref was made
  }
示例#15
0
  @Test
  public void testMapAccessorWithStaticFieldAccess() {
    String str =
        ""
            + "package org.test \n"
            + "import "
            + Person.class.getCanonicalName()
            + "\n"
            + "import "
            + Address.class.getCanonicalName()
            + "\n"
            + "import "
            + TestEnum.class.getCanonicalName()
            + "\n"
            + "global java.util.List list \n"
            + "rule \"show\" \n"
            + "when  \n"
            + "    $m : Person( namedAddresses[TestEnum.ONE] == new Address('s1'), namedAddresses[TestEnum.ONE].street == new Address('s1').street ) \n"
            + "then \n"
            + "    list.add('r1'); \n"
            + "end \n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal("list", list);

    Person p = new Person("yoda");
    p.getNamedAddresses().put(TestEnum.ONE, new Address("s1"));

    ksession.insert(p);

    ksession.fireAllRules();

    assertEquals("r1", list.get(0));

    // Check it was built with MVELReturnValueExpression constraint
    List<ObjectTypeNode> nodes =
        ((InternalRuleBase) ((KnowledgeBaseImpl) kbase).ruleBase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for (ObjectTypeNode n : nodes) {
      if (((ClassObjectType) n.getObjectType()).getClassType() == Person.class) {
        node = n;
        break;
      }
    }

    AlphaNode alphanode = (AlphaNode) node.getSinkPropagator().getSinks()[0];
    AlphaNodeFieldConstraint constraint = alphanode.getConstraint();

    if (constraint instanceof MvelConstraint) {
      assertTrue(
          ((MvelConstraint) alphanode.getConstraint()).getFieldExtractor()
              instanceof MVELObjectClassFieldReader);
      assertEquals(
          new Address("s1"), ((MvelConstraint) alphanode.getConstraint()).getField().getValue());
    }

    alphanode = (AlphaNode) alphanode.getSinkPropagator().getSinks()[0];
    constraint = alphanode.getConstraint();

    if (constraint instanceof MvelConstraint) {
      assertTrue(
          ((MvelConstraint) alphanode.getConstraint()).getFieldExtractor()
              instanceof MVELObjectClassFieldReader);
      assertEquals(
          new Address("s1").getStreet(),
          ((MvelConstraint) alphanode.getConstraint()).getField().getValue());
    }
  }
示例#16
0
 /* (non-Javadoc)
  * @see org.drools.management.ObjectTypeNodeMonitorMbean#getObjectType()
  */
 public String getObjectType() {
   return node.getObjectType().toString();
 }
示例#17
0
 /* (non-Javadoc)
  * @see org.drools.management.ObjectTypeNodeMonitorMbean#getPartitionId()
  */
 public String getPartitionId() {
   return node.getPartitionId().toString();
 }
示例#18
0
 /* (non-Javadoc)
  * @see org.drools.management.ObjectTypeNodeMonitorMbean#isEvent()
  */
 public boolean isEvent() {
   return node.getObjectType().isEvent();
 }
示例#19
0
 /* (non-Javadoc)
  * @see org.drools.management.ObjectTypeNodeMonitorMbean#getExpirationOffset()
  */
 public long getExpirationOffset() {
   return node.getExpirationOffset();
 }
示例#20
0
 /* (non-Javadoc)
  * @see org.drools.management.ObjectTypeNodeMonitorMbean#getEntryPoint()
  */
 public String getEntryPoint() {
   return node.getEntryPoint().toString();
 }
示例#21
0
 /**
  * Adds the <code>ObjectSink</code> so that it may receive <code>Objects</code> propagated from
  * this <code>ObjectSource</code>.
  *
  * @param objectSink The <code>ObjectSink</code> to receive propagated <code>Objects</code>. Rete
  *     only accepts <code>ObjectTypeNode</code>s as parameters to this method, though.
  */
 public void addObjectSink(final ObjectSink objectSink) {
   final ObjectTypeNode node = (ObjectTypeNode) objectSink;
   this.objectTypeNodes.put(node.getObjectType(), node);
 }
示例#22
0
 protected void removeObjectSink(final ObjectSink objectSink) {
   final ObjectTypeNode node = (ObjectTypeNode) objectSink;
   this.objectTypeNodes.remove(node.getObjectType());
 }
  public static ReteooStatefulSession readSession(
      ReteooStatefulSession session,
      DefaultAgenda agenda,
      long time,
      boolean multithread,
      MarshallerReaderContext context)
      throws IOException, ClassNotFoundException {
    if (session.getTimerService() instanceof PseudoClockScheduler) {
      PseudoClockScheduler clock = (PseudoClockScheduler) session.getTimerService();
      clock.advanceTime(time, TimeUnit.MILLISECONDS);
    }

    // RuleFlowGroups need to reference the session
    for (RuleFlowGroup group : agenda.getRuleFlowGroupsMap().values()) {
      ((RuleFlowGroupImpl) group).setWorkingMemory(session);
    }

    context.wm = session;

    context.handles.put(
        context.wm.getInitialFactHandle().getId(), context.wm.getInitialFactHandle());

    if (context.stream.readBoolean()) {
      InternalFactHandle initialFactHandle = context.wm.getInitialFactHandle();
      int sinkId = context.stream.readInt();
      ObjectTypeNode initialFactNode = (ObjectTypeNode) context.sinks.get(sinkId);
      if (initialFactNode == null) {
        // ------ START RANT ------
        // The following code is as bad as it looks, but since I was so far
        // unable to convince Mark that creating OTNs on demand is really bad,
        // I have to continue doing it :)
        EntryPointNode defaultEPNode =
            context.ruleBase.getRete().getEntryPointNode(EntryPoint.DEFAULT);
        BuildContext buildContext =
            new BuildContext(
                context.ruleBase, context.ruleBase.getReteooBuilder().getIdGenerator());
        buildContext.setPartitionId(RuleBasePartitionId.MAIN_PARTITION);
        buildContext.setObjectTypeNodeMemoryEnabled(true);
        initialFactNode =
            new ObjectTypeNode(
                sinkId, defaultEPNode, ClassObjectType.InitialFact_ObjectType, buildContext);
        // isn't contention something everybody loves?
        context.ruleBase.lock();
        try {
          // Yeah, I know, because one session is being deserialized, we go and lock all of them...
          initialFactNode.attach(buildContext);
        } finally {
          context.ruleBase.unlock();
        }
        // ------- END RANT -----
      }
      ObjectHashSet initialFactMemory = (ObjectHashSet) context.wm.getNodeMemory(initialFactNode);

      initialFactMemory.add(initialFactHandle);
      readRightTuples(initialFactHandle, context);
    }
    while (context.readShort() == PersisterEnums.ENTRY_POINT) {
      String entryPointId = context.stream.readUTF();
      WorkingMemoryEntryPoint wmep = context.wm.getEntryPoints().get(entryPointId);
      readFactHandles(context, ((NamedEntryPoint) wmep).getObjectStore());
    }
    InternalFactHandle handle = context.wm.getInitialFactHandle();
    while (context.stream.readShort() == PersisterEnums.LEFT_TUPLE) {
      LeftTupleSink sink = (LeftTupleSink) context.sinks.get(context.stream.readInt());
      LeftTuple leftTuple = sink.createLeftTuple(handle, sink, true);
      readLeftTuple(leftTuple, context);
    }

    readPropagationContexts(context);

    readActivations(context);

    readActionQueue(context);

    readTruthMaintenanceSystem(context);

    if (processMarshaller != null) {
      processMarshaller.readProcessInstances(context);
    } else {
      short type = context.stream.readShort();
      if (PersisterEnums.END != type) {
        throw new IllegalStateException(
            "No process marshaller, unable to unmarshall type: " + type);
      }
    }

    if (processMarshaller != null) {
      processMarshaller.readWorkItems(context);
    } else {
      short type = context.stream.readShort();
      if (PersisterEnums.END != type) {
        throw new IllegalStateException(
            "No process marshaller, unable to unmarshall type: " + type);
      }
    }

    if (processMarshaller != null) {
      // This actually does ALL timers, due to backwards compatability issues
      // It will read in old JBPM binaries, but always write to the new binary format.
      processMarshaller.readProcessTimers(context);
    } else {
      short type = context.stream.readShort();
      if (PersisterEnums.END != type) {
        throw new IllegalStateException(
            "No process marshaller, unable to unmarshall type: " + type);
      }
    }

    // no legacy jBPM timers, so handle locally
    while (context.readShort() == PersisterEnums.DEFAULT_TIMER) {
      InputMarshaller.readTimer(context);
    }

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

    return session;
  }
示例#24
0
 /* (non-Javadoc)
  * @see org.drools.management.ObjectTypeNodeMonitorMbean#getId()
  */
 public int getId() {
   return node.getId();
 }
  public void testQueryTerminalNode() {
    final ClassObjectType queryObjectType = new ClassObjectType(DroolsQuery.class);
    final ObjectTypeNode queryObjectTypeNode =
        new ObjectTypeNode(this.buildContext.getNextId(), queryObjectType, buildContext);
    queryObjectTypeNode.attach();

    ClassFieldExtractor extractor =
        cache.getExtractor(DroolsQuery.class, "name", DroolsQuery.class.getClassLoader());

    FieldValue field = FieldFactory.getFieldValue("query-1");

    final Evaluator evaluator = ValueType.STRING_TYPE.getEvaluator(Operator.EQUAL);
    LiteralConstraint constraint = new LiteralConstraint(extractor, evaluator, field);

    AlphaNode alphaNode =
        new AlphaNode(this.buildContext.getNextId(), constraint, queryObjectTypeNode, buildContext);
    alphaNode.attach();

    final LeftInputAdapterNode liaNode =
        new LeftInputAdapterNode(this.buildContext.getNextId(), alphaNode, this.buildContext);
    liaNode.attach();

    final ClassObjectType cheeseObjectType = new ClassObjectType(Cheese.class);
    final ObjectTypeNode cheeseObjectTypeNode =
        new ObjectTypeNode(this.buildContext.getNextId(), cheeseObjectType, buildContext);
    cheeseObjectTypeNode.attach();

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

    field = FieldFactory.getFieldValue("stilton");

    constraint = new LiteralConstraint(extractor, evaluator, field);

    alphaNode =
        new AlphaNode(
            this.buildContext.getNextId(), constraint, cheeseObjectTypeNode, buildContext);
    alphaNode.attach();

    BuildContext buildContext =
        new BuildContext(ruleBase, ruleBase.getReteooBuilder().getIdGenerator());
    buildContext.setTupleMemoryEnabled(false);

    final JoinNode joinNode =
        new JoinNode(
            this.buildContext.getNextId(),
            liaNode,
            alphaNode,
            EmptyBetaConstraints.getInstance(),
            buildContext);
    joinNode.attach();

    final Query query = new Query("query-1");

    final QueryTerminalNode queryNode =
        new QueryTerminalNode(this.buildContext.getNextId(), joinNode, query, query.getLhs());

    queryNode.attach();

    final org.drools.rule.Package pkg = new org.drools.rule.Package("com.drools.test");
    pkg.addRule(query);

    try {
      final Field pkgField = ruleBase.getClass().getSuperclass().getDeclaredField("pkgs");
      pkgField.setAccessible(true);
      final Map pkgs = (Map) pkgField.get(ruleBase);
      pkgs.put(pkg.getName(), pkg);
    } catch (final Exception e) {
      Assert.fail("Should not throw any exception: " + e.getMessage());
    }

    final WorkingMemory workingMemory = ruleBase.newStatefulSession();
    QueryResults results = workingMemory.getQueryResults("query-1");

    assertEquals(0, results.size());

    final Cheese stilton1 = new Cheese("stilton", 100);
    final FactHandle handle1 = workingMemory.insert(stilton1);

    results = workingMemory.getQueryResults("query-1");

    assertEquals(1, results.size());

    final Cheese cheddar = new Cheese("cheddar", 55);
    workingMemory.insert(cheddar);

    results = workingMemory.getQueryResults("query-1");

    assertEquals(1, results.size());

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

    final FactHandle handle2 = workingMemory.insert(stilton2);

    results = workingMemory.getQueryResults("query-1");

    assertEquals(2, results.size());

    QueryResult result = results.get(0);
    assertEquals(1, result.size());
    assertEquals(stilton2, result.get(0));

    result = results.get(1);
    assertEquals(1, result.size());
    assertEquals(stilton1, result.get(0));

    int i = 0;
    for (final Iterator it = results.iterator(); it.hasNext(); ) {
      result = (QueryResult) it.next();
      assertEquals(1, result.size());
      if (i == 1) {
        assertSame(stilton1, result.get(0));
      } else {
        assertSame(stilton2, result.get(0));
      }
      i++;
    }

    workingMemory.retract(handle1);
    results = workingMemory.getQueryResults("query-1");

    assertEquals(1, results.size());

    workingMemory.retract(handle2);
    results = workingMemory.getQueryResults("query-1");

    assertEquals(0, results.size());
  }
示例#26
0
  public void attachAlphaNodes(
      final BuildContext context,
      final BuildUtils utils,
      final Pattern pattern,
      List<Constraint> alphaConstraints)
      throws InvalidPatternException {

    // Drools Query ObjectTypeNode never has memory, but other ObjectTypeNode/AlphaNoesNodes may (if
    // not in sequential),
    // so need to preserve, so we can restore after this node is added. LeftMemory  and Terminal
    // remain the same once set.

    boolean objectMemory = context.isObjectTypeNodeMemoryEnabled();
    boolean alphaMemory = context.isAlphaMemoryAllowed();

    ObjectType objectType = pattern.getObjectType();

    if (pattern.getObjectType() instanceof ClassObjectType) {
      // Is this the query node, if so we don't want any memory
      if (DroolsQuery.class == ((ClassObjectType) pattern.getObjectType()).getClassType()) {
        context.setTupleMemoryEnabled(false);
        context.setObjectTypeNodeMemoryEnabled(false);
        context.setTerminalNodeMemoryEnabled(false);
        context.setAlphaNodeMemoryAllowed(false);
      }
    }

    context.setObjectSource(
        (ObjectSource)
            utils.attachNode(
                context,
                new EntryPointNode(context.getNextId(), context.getRuleBase().getRete(), context)));

    ObjectTypeNode otn =
        new ObjectTypeNode(
            context.getNextId(), (EntryPointNode) context.getObjectSource(), objectType, context);
    if (objectType.isEvent()
        && EventProcessingOption.STREAM.equals(
            context.getRuleBase().getConfiguration().getEventProcessingMode())) {
      long expirationOffset = getExpiratioOffsetForType(context, objectType);
      if (expirationOffset != -1) {
        // expiration policy is set, so use it
        otn.setExpirationOffset(expirationOffset);
      } else {
        // otherwise calculate it based on behaviours and temporal constraints
        for (Behavior behavior : pattern.getBehaviors()) {
          if (behavior.getExpirationOffset() != -1) {
            expirationOffset = Math.max(behavior.getExpirationOffset(), expirationOffset);
          }
        }
        long distance = context.getTemporalDistance().getExpirationOffset(pattern);
        if (distance == -1) {
          // it means the rules have no temporal constraints, or
          // the constraints require events to be hold forever. In this
          // case, we allow type declarations to override the implicit
          // expiration offset by defining an expiration policy with the
          // @expires tag
          otn.setExpirationOffset(expirationOffset);
        } else {
          otn.setExpirationOffset(Math.max(distance, expirationOffset));
        }
      }
    }

    context.setObjectSource((ObjectSource) utils.attachNode(context, otn));

    for (final Iterator<Constraint> it = alphaConstraints.iterator(); it.hasNext(); ) {
      final AlphaNodeFieldConstraint constraint = (AlphaNodeFieldConstraint) it.next();

      context.pushRuleComponent(constraint);
      context.setObjectSource(
          (ObjectSource)
              utils.attachNode(
                  context,
                  new AlphaNode(
                      context.getNextId(),
                      (AlphaNodeFieldConstraint) constraint,
                      context.getObjectSource(),
                      context)));
      context.popRuleComponent();
    }

    // now restore back to original values
    context.setObjectTypeNodeMemoryEnabled(objectMemory);
    context.setAlphaNodeMemoryAllowed(alphaMemory);
  }