public void testLiteralConstraintAssertSequentialMode() throws Exception {
    RuleBaseConfiguration config = new RuleBaseConfiguration();
    config.setSequential(true);
    ReteooRuleBase ruleBase = (ReteooRuleBase) RuleBaseFactory.newRuleBase(config);
    BuildContext buildContext =
        new BuildContext(ruleBase, ((ReteooRuleBase) ruleBase).getReteooBuilder().getIdGenerator());
    ReteooWorkingMemory workingMemory = new ReteooWorkingMemory(buildContext.getNextId(), ruleBase);

    final Rule rule = new Rule("test-rule");
    final PropagationContext context =
        new PropagationContextImpl(0, PropagationContext.ASSERTION, null, null);

    final MockObjectSource source = new MockObjectSource(buildContext.getNextId());

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

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

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

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

    // With Memory
    final AlphaNode alphaNode =
        new AlphaNode(buildContext.getNextId(), constraint, source, buildContext); // has memory

    final MockObjectSink sink = new MockObjectSink();
    alphaNode.addObjectSink(sink);

    final Cheese cheddar = new Cheese("cheddar", 5);
    final DefaultFactHandle f0 = (DefaultFactHandle) workingMemory.insert(cheddar);

    // check sink is empty
    assertLength(0, sink.getAsserted());

    // check alpha memory is empty
    final AlphaMemory memory = (AlphaMemory) workingMemory.getNodeMemory(alphaNode);

    assertNull(memory.facts);

    // object should assert as it passes text
    alphaNode.assertObject(f0, context, workingMemory);

    assertEquals(1, sink.getAsserted().size());
    assertNull(memory.facts);
    Object[] list = (Object[]) sink.getAsserted().get(0);
    assertSame(cheddar, workingMemory.getObject((DefaultFactHandle) list[0]));

    final Cheese stilton = new Cheese("stilton", 6);
    final DefaultFactHandle f1 = new DefaultFactHandle(1, stilton);

    // object should NOT assert as it does not pass test
    alphaNode.assertObject(f1, context, workingMemory);

    assertLength(1, sink.getAsserted());
    assertNull(memory.facts);
    list = (Object[]) sink.getAsserted().get(0);
    assertSame(cheddar, workingMemory.getObject((DefaultFactHandle) list[0]));
  }
  public void testRetractObjectWithMemory() throws Exception {
    RuleBaseConfiguration config = new RuleBaseConfiguration();
    config.setAlphaMemory(true);
    ReteooRuleBase ruleBase = (ReteooRuleBase) RuleBaseFactory.newRuleBase(config);
    BuildContext buildContext =
        new BuildContext(ruleBase, ((ReteooRuleBase) ruleBase).getReteooBuilder().getIdGenerator());
    ReteooWorkingMemory workingMemory = (ReteooWorkingMemory) ruleBase.newStatefulSession();

    final Rule rule = new Rule("test-rule");
    final PropagationContext context =
        new PropagationContextImpl(0, PropagationContext.ASSERTION, null, null);

    final MockObjectSource source = new MockObjectSource(buildContext.getNextId());

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

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

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

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

    buildContext.setAlphaNodeMemoryAllowed(true);
    final AlphaNode alphaNode =
        new AlphaNode(buildContext.getNextId(), constraint, source, buildContext); // has memory
    final MockObjectSink sink = new MockObjectSink();
    alphaNode.addObjectSink(sink);

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

    final DefaultFactHandle f0 = new DefaultFactHandle(0, cheddar);

    // check alpha memory is empty
    final AlphaMemory memory = (AlphaMemory) workingMemory.getNodeMemory(alphaNode);
    assertEquals(0, memory.facts.size());

    // object should assert as it passes text
    alphaNode.assertObject(f0, context, workingMemory);

    assertEquals(1, memory.facts.size());

    final DefaultFactHandle f1 = new DefaultFactHandle(1, "cheese");

    // object should NOT retract as it doesn't exist
    alphaNode.retractObject(f1, context, workingMemory);

    assertLength(0, sink.getRetracted());
    assertEquals(1, memory.facts.size());
    assertTrue("Should contain 'cheddar handle'", memory.facts.contains(f0));

    // object should retract as it does exist
    alphaNode.retractObject(f0, context, workingMemory);

    assertLength(1, sink.getRetracted());
    assertEquals(0, memory.facts.size());
    final Object[] list = (Object[]) sink.getRetracted().get(0);
    assertSame(f0, list[0]);
  }
示例#3
0
  @Test
  public void testLiteralConstraintAssertObjectWithoutMemory() throws Exception {
    ReteooRuleBase ruleBase = (ReteooRuleBase) RuleBaseFactory.newRuleBase();
    BuildContext buildContext =
        new BuildContext(ruleBase, ((ReteooRuleBase) ruleBase).getReteooBuilder().getIdGenerator());
    ReteooWorkingMemory workingMemory = (ReteooWorkingMemory) ruleBase.newStatefulSession();

    final Rule rule = new Rule("test-rule");
    final PropagationContext context =
        new PropagationContextImpl(0, PropagationContext.INSERTION, null, null, null);

    final MockObjectSource source = new MockObjectSource(buildContext.getNextId());

    final ClassFieldReader extractor =
        store.getReader(Cheese.class, "type", getClass().getClassLoader());

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

    final MvelConstraint constraint =
        new MvelConstraintTestUtil("type == \"cheddar\"", field, extractor);

    // With Memory
    final AlphaNode alphaNode =
        new AlphaNode(buildContext.getNextId(), constraint, source, buildContext); // no memory

    final MockObjectSink sink = new MockObjectSink();
    alphaNode.addObjectSink(sink);

    final Cheese cheddar = new Cheese("cheddar", 5);
    final DefaultFactHandle f0 = (DefaultFactHandle) workingMemory.insert(cheddar);

    // check sink is empty
    assertLength(0, sink.getAsserted());

    // check alpha memory is empty
    final AlphaMemory memory = (AlphaMemory) workingMemory.getNodeMemory(alphaNode);

    // object should assert as it passes text
    alphaNode.assertObject(f0, context, workingMemory);

    assertEquals(1, sink.getAsserted().size());

    Object[] list = (Object[]) sink.getAsserted().get(0);
    assertSame(cheddar, workingMemory.getObject((DefaultFactHandle) list[0]));

    final Cheese stilton = new Cheese("stilton", 6);
    final DefaultFactHandle f1 = new DefaultFactHandle(1, stilton);

    // object should NOT assert as it does not pass test
    alphaNode.assertObject(f1, context, workingMemory);

    assertLength(1, sink.getAsserted());

    list = (Object[]) sink.getAsserted().get(0);
    assertSame(cheddar, workingMemory.getObject((DefaultFactHandle) list[0]));
  }
  /*
   * dont need to test with and without memory on this, as it was already done
   * on the previous two tests. This just test AlphaNode With a different
   * Constraint type.
   */
  public void testReturnValueConstraintAssertObject() throws Exception {
    RuleBaseConfiguration config = new RuleBaseConfiguration();
    config.setAlphaMemory(false);
    ReteooRuleBase ruleBase = (ReteooRuleBase) RuleBaseFactory.newRuleBase(config);
    BuildContext buildContext =
        new BuildContext(ruleBase, ((ReteooRuleBase) ruleBase).getReteooBuilder().getIdGenerator());
    ReteooWorkingMemory workingMemory = (ReteooWorkingMemory) ruleBase.newStatefulSession();

    final Rule rule = new Rule("test-rule");
    final PropagationContext context =
        new PropagationContextImpl(0, PropagationContext.ASSERTION, null, null);

    final MockObjectSource source = new MockObjectSource(buildContext.getNextId());

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

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

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

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

    final AlphaNode alphaNode =
        new AlphaNode(buildContext.getNextId(), constraint, source, buildContext);
    final MockObjectSink sink = new MockObjectSink();
    alphaNode.addObjectSink(sink);

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

    final DefaultFactHandle f0 = (DefaultFactHandle) workingMemory.insert(cheddar);

    assertLength(0, sink.getAsserted());

    // object should assert as it passes text
    alphaNode.assertObject(f0, context, workingMemory);

    assertLength(1, sink.getAsserted());
    final Object[] list = (Object[]) sink.getAsserted().get(0);
    assertSame(cheddar, workingMemory.getObject((DefaultFactHandle) list[0]));

    final Cheese stilton = new Cheese("stilton", 6);
    f0.setObject(stilton);

    sink.getAsserted().clear();

    // object should not assert as it does not pass text
    alphaNode.assertObject(f0, context, workingMemory);

    assertLength(0, sink.getAsserted());
  }
  public void testIsMemoryAllowedOverride() throws Exception {
    RuleBaseConfiguration config = new RuleBaseConfiguration();
    config.setAlphaMemory(true);
    ReteooRuleBase ruleBase = (ReteooRuleBase) RuleBaseFactory.newRuleBase(config);
    BuildContext buildContext =
        new BuildContext(ruleBase, ((ReteooRuleBase) ruleBase).getReteooBuilder().getIdGenerator());
    ReteooWorkingMemory workingMemory = (ReteooWorkingMemory) ruleBase.newStatefulSession();

    final Rule rule = new Rule("test-rule");
    final PropagationContext context =
        new PropagationContextImpl(0, PropagationContext.ASSERTION, null, null);

    final MockObjectSource source = new MockObjectSource(buildContext.getNextId());

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

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

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

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

    // With Memory
    buildContext.setAlphaNodeMemoryAllowed(false);
    final AlphaNode alphaNode =
        new AlphaNode(buildContext.getNextId(), constraint, source, buildContext); // has memory

    final MockObjectSink sink = new MockObjectSink();
    alphaNode.addObjectSink(sink);

    final Cheese cheddar = new Cheese("cheddar", 5);
    final DefaultFactHandle f0 = (DefaultFactHandle) workingMemory.insert(cheddar);

    // check sink is empty
    assertLength(0, sink.getAsserted());

    // check alpha memory is empty
    final AlphaMemory memory = (AlphaMemory) workingMemory.getNodeMemory(alphaNode);

    assertNull(memory.facts);

    // object should assert as it passes text
    alphaNode.assertObject(f0, context, workingMemory);

    assertEquals(1, sink.getAsserted().size());
    // memory should be one, as even though isAlphaMemory is on for the configuration, the build
    // never allows memory
    assertNull(memory.facts);
  }
  public void testMemory() {
    RuleBaseConfiguration config = new RuleBaseConfiguration();
    config.setAlphaMemory(false);
    ReteooRuleBase ruleBase = (ReteooRuleBase) RuleBaseFactory.newRuleBase(config);
    BuildContext buildContext =
        new BuildContext(ruleBase, ((ReteooRuleBase) ruleBase).getReteooBuilder().getIdGenerator());
    ReteooWorkingMemory workingMemory = (ReteooWorkingMemory) ruleBase.newStatefulSession();

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

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

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

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

    final AlphaNode alphaNode =
        new AlphaNode(buildContext.getNextId(), constraint, null, buildContext);

    final AlphaMemory memory = (AlphaMemory) workingMemory.getNodeMemory(alphaNode);

    assertNotNull(memory);
  }
  public void execute(Map<String, Object> context, List<String[]> args) {
    BuildContext buildContext = (BuildContext) context.get("BuildContext");

    if (args.size() >= 1) {

      // The first argument list is the node parameters
      String[] a = args.get(0);
      String name = a[0];
      String leftInput = a[1];
      String rightInput = a[2];
      String sourceType = a[3];
      String expr = a[4];

      LeftTupleSource leftTupleSource;
      if ("mock".equals(leftInput)) {
        leftTupleSource = Mockito.mock(LeftTupleSource.class);
      } else {
        leftTupleSource = (LeftTupleSource) context.get(leftInput);
      }

      ObjectSource rightObjectSource;
      if ("mock".equals(rightInput)) {
        rightObjectSource = Mockito.mock(ObjectSource.class);
      } else {
        rightObjectSource = (ObjectSource) context.get(rightInput);
      }

      Pattern sourcePattern;
      Pattern resultPattern;
      try {
        sourcePattern = reteTesterHelper.getPattern(0, sourceType);

        // we always use the accumulate function "sum", so return type is always Number
        resultPattern =
            reteTesterHelper.getPattern(buildContext.getNextId(), Number.class.getName());
      } catch (Exception e) {
        throw new IllegalArgumentException(
            "Not possible to process arguments: " + Arrays.toString(a));
      }

      BetaConstraints betaSourceConstraints = new EmptyBetaConstraints();
      AlphaNodeFieldConstraint[] alphaResultConstraint = new AlphaNodeFieldConstraint[0];
      // the following arguments are constraints
      for (int i = 1; i < args.size(); i++) {
        a = args.get(i);
        String type = a[0];
        String fieldName = a[1];
        String operator = a[2];
        String val = a[3];

        if ("source".equals(type)) {
          Declaration declr = (Declaration) context.get(val);
          try {
            BetaNodeFieldConstraint sourceBetaConstraint =
                this.reteTesterHelper.getBoundVariableConstraint(
                    sourcePattern, fieldName, declr, operator);
            betaSourceConstraints =
                new SingleBetaConstraints(
                    sourceBetaConstraint, buildContext.getRuleBase().getConfiguration());
          } catch (IntrospectionException e) {
            throw new IllegalArgumentException();
          }
        } else if ("result".equals(type)) {
          alphaResultConstraint = new AlphaNodeFieldConstraint[1];
          try {
            alphaResultConstraint[0] =
                this.reteTesterHelper.getLiteralConstraint(resultPattern, fieldName, operator, val);
          } catch (IntrospectionException e) {
            throw new IllegalArgumentException(
                "Unable to configure alpha constraint: " + Arrays.toString(a), e);
          }
        }
      }

      NodeTestCase testCase = (NodeTestCase) context.get("TestCase");
      List<String> classImports = new ArrayList<String>();
      List<String> pkgImports = new ArrayList<String>();
      for (String imp : testCase.getImports()) {
        if (imp.endsWith(".*")) {
          pkgImports.add(imp.substring(0, imp.lastIndexOf('.')));
        } else {
          classImports.add(imp);
        }
      }

      // build an external function executor
      MVELCompilationUnit compilationUnit =
          new MVELCompilationUnit(
              name,
              expr,
              pkgImports.toArray(new String[0]), // pkg imports
              classImports.toArray(new String[0]), // imported classes
              new String[] {}, // imported methods
              new String[] {}, // imported fields
              new String[] {}, // global identifiers
              new Declaration[] {}, // previous declarations
              new Declaration[] {(Declaration) context.get(expr)}, // local declarations
              new String[] {}, // other identifiers
              new String[] {}, // input identifiers
              new String[] {}, // input types
              4,
              false);

      AccumulateFunction accFunction = new SumAccumulateFunction();

      Accumulator accumulator = new MVELAccumulatorFunctionExecutor(compilationUnit, accFunction);
      ((MVELCompileable) accumulator).compile(Thread.currentThread().getContextClassLoader());

      Accumulate accumulate =
          new Accumulate(
              sourcePattern,
              new Declaration[] {}, // required declaration
              new Declaration[] {}, // inner declarations
              new Accumulator[] {accumulator});
      AccumulateNode accNode =
          new AccumulateNode(
              buildContext.getNextId(),
              leftTupleSource,
              rightObjectSource,
              alphaResultConstraint,
              betaSourceConstraints,
              new EmptyBetaConstraints(),
              new Behavior[] {},
              accumulate,
              false,
              buildContext);

      accNode.attach();
      context.put(name, accNode);

    } else {
      StringBuilder msgBuilder = new StringBuilder();
      msgBuilder.append("Can not parse AccumulateNode step arguments: \n");
      for (String[] arg : args) {
        msgBuilder.append("    ");
        msgBuilder.append(Arrays.toString(arg));
        msgBuilder.append("\n");
      }
      throw new IllegalArgumentException(msgBuilder.toString());
    }
  }
示例#8
0
  @Test
  public void testUpdateSinkWithoutMemory() throws FactException, IntrospectionException {
    // An AlphaNode should try and repropagate from its source
    ReteooRuleBase ruleBase = (ReteooRuleBase) RuleBaseFactory.newRuleBase();
    BuildContext buildContext =
        new BuildContext(ruleBase, ((ReteooRuleBase) ruleBase).getReteooBuilder().getIdGenerator());
    ReteooWorkingMemory workingMemory = (ReteooWorkingMemory) ruleBase.newStatefulSession();

    final Rule rule = new Rule("test-rule");
    final PropagationContext context =
        new PropagationContextImpl(0, PropagationContext.INSERTION, null, null, null);

    final MockObjectSource source = new MockObjectSource(buildContext.getNextId());

    final InternalReadAccessor extractor =
        store.getReader(Cheese.class, "type", getClass().getClassLoader());

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

    final MvelConstraint constraint =
        new MvelConstraintTestUtil("type == \"cheddar\"", field, extractor);

    final AlphaNode alphaNode =
        new AlphaNode(buildContext.getNextId(), constraint, source, buildContext); // no memory

    alphaNode.attach();

    final MockObjectSink sink1 = new MockObjectSink();
    alphaNode.addObjectSink(sink1);

    // Assert a single fact which should be in the AlphaNode memory and also
    // propagated to the
    // the tuple sink
    final Cheese cheese = new Cheese("cheddar", 0);
    final DefaultFactHandle handle1 = new DefaultFactHandle(1, cheese);
    // adding handle to the mock source
    source.addFact(handle1);

    alphaNode.assertObject(handle1, context, workingMemory);

    // Create a fact that should not be propagated, since the alpha node restriction will filter it
    // out
    final Cheese stilton = new Cheese("stilton", 10);
    final DefaultFactHandle handle2 = new DefaultFactHandle(2, stilton);
    // adding handle to the mock source
    source.addFact(handle2);

    alphaNode.assertObject(handle2, context, workingMemory);

    assertLength(1, sink1.getAsserted());

    // Attach a new tuple sink
    final MockObjectSink sink2 = new MockObjectSink();

    // Tell the alphanode to update the new node. Make sure the first sink1
    // is not updated
    // likewise the source should not do anything
    alphaNode.updateSink(sink2, context, workingMemory);

    assertLength(1, sink1.getAsserted());
    assertLength(1, sink2.getAsserted());
    assertEquals(1, source.getUdated());
  }
  public void testUpdateSinkWithMemory() throws FactException, IntrospectionException {
    // An AlphaNode with memory should not try and repropagate from its source
    // Also it should only update the latest tuple sinky
    RuleBaseConfiguration config = new RuleBaseConfiguration();
    config.setAlphaMemory(true);
    ReteooRuleBase ruleBase = (ReteooRuleBase) RuleBaseFactory.newRuleBase(config);
    BuildContext buildContext =
        new BuildContext(ruleBase, ((ReteooRuleBase) ruleBase).getReteooBuilder().getIdGenerator());
    ReteooWorkingMemory workingMemory = (ReteooWorkingMemory) ruleBase.newStatefulSession();

    final Rule rule = new Rule("test-rule");
    final PropagationContext context =
        new PropagationContextImpl(0, PropagationContext.ASSERTION, null, null);

    final MockObjectSource source = new MockObjectSource(buildContext.getNextId());

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

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

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

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

    buildContext.setAlphaNodeMemoryAllowed(true);
    final AlphaNode alphaNode =
        new AlphaNode(buildContext.getNextId(), constraint, source, buildContext); // has memory

    alphaNode.attach();

    final MockObjectSink sink1 = new MockObjectSink();
    alphaNode.addObjectSink(sink1);

    // Assert a single fact which should be in the AlphaNode memory and also
    // propagated to the
    // the tuple sink
    final Cheese cheese = new Cheese("cheddar", 0);
    final DefaultFactHandle handle1 = new DefaultFactHandle(1, cheese);

    alphaNode.assertObject(handle1, context, workingMemory);

    // Create a fact that should not be propagated, since the alpha node restriction will filter it
    // out
    final Cheese stilton = new Cheese("stilton", 10);
    final DefaultFactHandle handle2 = new DefaultFactHandle(2, stilton);
    // adding handle to the mock source
    source.addFact(handle2);

    alphaNode.assertObject(handle2, context, workingMemory);
    assertLength(1, sink1.getAsserted());

    // Attach a new tuple sink
    final MockObjectSink sink2 = new MockObjectSink();

    // Tell the alphanode to update the new node. Make sure the first sink1
    // is not updated
    // likewise the source should not do anything
    alphaNode.updateSink(sink2, context, workingMemory);

    assertLength(1, sink1.getAsserted());
    assertLength(1, sink2.getAsserted());
    assertEquals(0, source.getUdated());
  }