コード例 #1
0
ファイル: ReteAgenda.java プロジェクト: chearius/drools
  public void addActivation(AgendaItem item, boolean notify) {
    RuleImpl rule = item.getRule();
    item.setQueued(true);

    // set the focus if rule autoFocus is true
    if (rule.getAutoFocus()) {
      this.setFocus(item.getPropagationContext(), rule.getAgendaGroup());
    }

    // adds item to activation group if appropriate
    addItemToActivationGroup(item);

    final Timer timer = rule.getTimer();
    if (timer != null && item instanceof ScheduledAgendaItem) {
      ScheduledAgendaItem sitem = (ScheduledAgendaItem) item;
      if (sitem.isEnqueued()) {
        // it's about to be re-added to scheduled list, so remove first
        this.scheduledActivations.remove(sitem);
      }
      scheduleItem(sitem, workingMemory);
    } else {
      addAgendaItemToGroup(item);
    }
    if (notify) {
      // if an activation is currently firing allows to completely fire it before to send the notify
      if (isFiringActivation) {
        mustNotifyHalt = true;
      } else {
        notifyHalt();
      }
    }
  }
コード例 #2
0
  public static ProtobufMessages.Activation writeActivation(
      MarshallerWriteContext context, AgendaItem agendaItem) {
    ProtobufMessages.Activation.Builder _activation = ProtobufMessages.Activation.newBuilder();

    RuleImpl rule = agendaItem.getRule();
    _activation.setPackageName(rule.getPackage());
    _activation.setRuleName(rule.getName());
    _activation.setTuple(writeTuple(agendaItem.getTuple()));
    _activation.setSalience(agendaItem.getSalience());
    _activation.setIsActivated(agendaItem.isQueued());
    _activation.setEvaluated(agendaItem.isRuleAgendaItem());

    if (agendaItem.getActivationGroupNode() != null) {
      _activation.setActivationGroup(
          agendaItem.getActivationGroupNode().getActivationGroup().getName());
    }

    if (agendaItem.getFactHandle() != null) {
      _activation.setHandleId(agendaItem.getFactHandle().getId());
    }

    org.drools.core.util.LinkedList<LogicalDependency> list = agendaItem.getLogicalDependencies();
    if (list != null && !list.isEmpty()) {
      for (LogicalDependency node = list.getFirst(); node != null; node = node.getNext()) {
        _activation.addLogicalDependency(((BeliefSet) node.getJustified()).getFactHandle().getId());
      }
    }
    return _activation.build();
  }
コード例 #3
0
ファイル: RuleTest.java プロジェクト: mok89/drools
  @Test
  public void testIsSalienceDynamic() {
    final RuleImpl rule = new RuleImpl("myrule");

    Salience salience = new MVELSalienceExpression();
    rule.setSalience(salience);

    assertTrue(rule.isSalienceDynamic());
  }
コード例 #4
0
 public Collection<Query> getQueries() {
   List<Query> list = new ArrayList<Query>(rules.size());
   for (RuleImpl rule : rules.values()) {
     if (rule.isQuery()) {
       list.add(rule);
     }
   }
   return Collections.unmodifiableCollection(list);
 }
コード例 #5
0
 private List<RuleImpl> getRulesGeneratedFromResource(Resource resource) {
   List<RuleImpl> rulesFromResource = new ArrayList<RuleImpl>();
   for (RuleImpl rule : rules.values()) {
     if (resource.equals(rule.getResource())) {
       rulesFromResource.add(rule);
     }
   }
   return rulesFromResource;
 }
コード例 #6
0
ファイル: RuleTest.java プロジェクト: mok89/drools
  @Test
  public void testDateEffectiveExpires() {
    WorkingMemory wm = new KnowledgeBaseImpl("x", null).newStatefulSession();

    final RuleImpl rule = new RuleImpl("myrule");

    final Calendar past = Calendar.getInstance();
    past.setTimeInMillis(10);

    final Calendar future = Calendar.getInstance();
    future.setTimeInMillis(future.getTimeInMillis() + 100000000);

    rule.setDateEffective(past);
    rule.setDateExpires(future);

    assertTrue(rule.isEffective(null, new RuleTerminalNode(), wm));

    rule.setDateExpires(past);
    assertFalse(rule.isEffective(null, new RuleTerminalNode(), wm));

    rule.setDateExpires(future);
    rule.setDateEffective(future);

    assertFalse(rule.isEffective(null, new RuleTerminalNode(), wm));
  }
コード例 #7
0
ファイル: RuleTest.java プロジェクト: mok89/drools
  @Test
  public void testGetSalienceValue() {
    final RuleImpl rule = new RuleImpl("myrule");
    final int salienceValue = 100;

    Salience salience = new SalienceInteger(salienceValue);
    rule.setSalience(salience);

    assertEquals(salienceValue, rule.getSalienceValue());
    assertFalse(rule.isSalienceDynamic());
  }
コード例 #8
0
  @Test
  public void testMVELDebugSymbols() throws DroolsParserException {

    MVELDebugHandler.setDebugMode(true);

    try {
      final DrlParser parser = new DrlParser(LanguageLevelOption.DRL5);
      final PackageDescr pkgDescr =
          parser.parse(new InputStreamReader(getClass().getResourceAsStream("mvel_rule.drl")));

      // just checking there is no parsing errors
      assertFalse(parser.getErrors().toString(), parser.hasErrors());

      InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.drools");

      final RuleDescr ruleDescr = pkgDescr.getRules().get(0);

      final RuleBuilder builder = new RuleBuilder();

      final KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg);
      final KnowledgeBuilderConfigurationImpl conf = pkgBuilder.getBuilderConfiguration();
      DialectCompiletimeRegistry dialectRegistry =
          pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
      Dialect dialect = dialectRegistry.getDialect("mvel");

      RuleBuildContext context =
          new RuleBuildContext(pkgBuilder, ruleDescr, dialectRegistry, pkg, dialect);

      builder.build(context);

      assertTrue(context.getErrors().toString(), context.getErrors().isEmpty());

      final RuleImpl rule = context.getRule();

      MVELConsequence mvelCons = (MVELConsequence) rule.getConsequence();
      mvelCons.compile(
          (MVELDialectRuntimeData)
              pkgBuilder
                  .getPackageRegistry(pkg.getName())
                  .getDialectRuntimeRegistry()
                  .getDialectData("mvel"));
      String s = DebugTools.decompile(mvelCons.getCompExpr());

      int fromIndex = 0;
      int count = 0;
      while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
        count++;
      }
      assertEquals(4, count);
    } finally {
      MVELDebugHandler.setDebugMode(false);
    }
  }
コード例 #9
0
  private int updateResourcesIncrementally(
      InternalKieModule currentKM,
      InternalKieModule newKM,
      KieJarChangeSet cs,
      List<String> modifiedClasses,
      KieBase kBase,
      KieBaseModel kieBaseModel,
      KnowledgeBuilderImpl kbuilder,
      CompositeKnowledgeBuilder ckbuilder) {
    int fileCount = modifiedClasses.size();
    for (ResourceChangeSet rcs : cs.getChanges().values()) {
      if (rcs.getChangeType() != ChangeType.REMOVED) {
        String resourceName = rcs.getResourceName();
        if (!resourceName.endsWith(".properties")
            && isFileInKBase(newKM, kieBaseModel, resourceName)) {
          List<ResourceChange> changes = rcs.getChanges();
          if (!changes.isEmpty()) {
            // we need to deal with individual parts of the resource
            fileCount +=
                AbstractKieModule.updateResource(ckbuilder, newKM, resourceName, rcs) ? 1 : 0;
          } else {
            // the whole resource has to handled
            if (rcs.getChangeType() == ChangeType.UPDATED) {
              Resource resource = currentKM.getResource(resourceName);
              kbuilder.removeObjectsGeneratedFromResource(resource);
            }
            fileCount += newKM.addResourceToCompiler(ckbuilder, kieBaseModel, resourceName) ? 1 : 0;
          }
        }
      }

      for (ResourceChangeSet.RuleLoadOrder loadOrder : rcs.getLoadOrder()) {
        KnowledgePackageImpl pkg =
            (KnowledgePackageImpl) kBase.getKiePackage(loadOrder.getPkgName());
        if (pkg != null) {
          RuleImpl rule = pkg.getRule(loadOrder.getRuleName());
          if (rule != null) {
            // rule can be null, if it didn't exist before
            rule.setLoadOrder(loadOrder.getLoadOrder());
          }
        }
      }
    }
    return fileCount;
  }
コード例 #10
0
  private void setupTest(String consequence, Map<String, Object> namedConsequences) {
    builder = new MVELConsequenceBuilder();

    InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.drools.compiler.test");
    pkg.addImport(new ImportDeclaration(Cheese.class.getCanonicalName()));

    KnowledgeBuilderConfigurationImpl conf = new KnowledgeBuilderConfigurationImpl();
    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg, conf);

    ruleDescr = new RuleDescr("test consequence builder");
    ruleDescr.setConsequence(consequence);
    ruleDescr.addAttribute(new AttributeDescr("dialect", "mvel"));

    for (Entry<String, Object> entry : namedConsequences.entrySet()) {
      ruleDescr.addNamedConsequences(entry.getKey(), entry.getValue());
    }

    RuleImpl rule = new RuleImpl(ruleDescr.getName());
    rule.addPattern(new Pattern(0, new ClassObjectType(Cheese.class), "$cheese"));

    rule.addPattern(new Pattern(0, new ClassObjectType(Map.class), "$map"));

    PackageRegistry pkgRegistry = pkgBuilder.getPackageRegistry(pkg.getName());
    DialectCompiletimeRegistry reg =
        pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    context =
        new RuleBuildContext(
            pkgBuilder, ruleDescr, reg, pkg, reg.getDialect(pkgRegistry.getDialect()));
    context.getBuildStack().push(rule.getLhs());

    context.getDialect().getConsequenceBuilder().build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);
    for (String name : namedConsequences.keySet()) {
      context.getDialect().getConsequenceBuilder().build(context, name);
    }

    context.getDialect().addRule(context);
    pkgRegistry.getPackage().addRule(context.getRule());
    pkgBuilder.compileAll();
    pkgBuilder.reloadAll();
    if (pkgBuilder.hasErrors()) {
      fail(pkgBuilder.getErrors().toString());
    }
  }
コード例 #11
0
  private boolean cancelAndContinue(
      InternalWorkingMemory wm,
      RuleTerminalNode rtn,
      RuleImpl rule,
      LeftTuple leftTuple,
      PropagationContext pctx,
      AgendaFilter filter) {
    // NB. stopped setting the LT.object to Boolean.TRUE, that Reteoo did.
    if (!rule.isEffective(leftTuple, rtn, wm)) {
      return true;
    }

    if (rule.getCalendars() != null) {
      long timestamp = wm.getSessionClock().getCurrentTime();
      for (String cal : rule.getCalendars()) {
        if (!wm.getCalendars().get(cal).isTimeIncluded(timestamp)) {
          return true;
        }
      }
    }

    return filter != null && !filter.accept((Activation) leftTuple);
  }
コード例 #12
0
  static RuleTerminalNode buildTerminalNodeForNamedConsequence(
      BuildContext context, NamedConsequence namedConsequence) {
    RuleImpl rule = context.getRule();
    GroupElement subrule = (GroupElement) context.peek();

    ActivationListenerFactory factory =
        context
            .getKnowledgeBase()
            .getConfiguration()
            .getActivationListenerFactory(rule.getActivationListener());

    context.setConsequenceName(namedConsequence.getConsequenceName());
    TerminalNode terminal =
        factory.createActivationListener(
            context.getNextId(),
            context.getTupleSource(),
            rule,
            subrule,
            0, // subruleIndex,
            context);
    context.setConsequenceName(null);

    return (RuleTerminalNode) terminal;
  }
コード例 #13
0
ファイル: RuleTest.java プロジェクト: mok89/drools
  @Test
  public void testRuleEnabled() {
    WorkingMemory wm = new KnowledgeBaseImpl("x", null).newStatefulSession();

    final RuleImpl rule = new RuleImpl("myrule");
    rule.setEnabled(EnabledBoolean.ENABLED_FALSE);
    assertFalse(rule.isEffective(null, new RuleTerminalNode(), wm));

    final Calendar past = Calendar.getInstance();
    past.setTimeInMillis(10);

    rule.setDateEffective(past);
    assertFalse(rule.isEffective(null, new RuleTerminalNode(), wm));
    rule.setEnabled(EnabledBoolean.ENABLED_TRUE);

    assertTrue(rule.isEffective(null, new RuleTerminalNode(), wm));
  }
コード例 #14
0
ファイル: ReteAgenda.java プロジェクト: chearius/drools
  public boolean createPostponedActivation(
      final LeftTuple tuple,
      final PropagationContext context,
      final InternalWorkingMemory workingMemory,
      final TerminalNode rtn) {

    final RuleImpl rule = rtn.getRule();
    AgendaItem item;
    if (rule.getCalendars() != null) {
      // for normal activations check for Calendar inclusion here, scheduled activations check on
      // each trigger point
      long timestamp = workingMemory.getSessionClock().getCurrentTime();
      for (String cal : rule.getCalendars()) {
        if (!workingMemory.getCalendars().get(cal).isTimeIncluded(timestamp)) {
          return false;
        }
      }
    }

    InternalAgendaGroup agendaGroup = (InternalAgendaGroup) getAgendaGroup(rule.getAgendaGroup());
    // do not add the activation if the rule is "lock-on-active" and the AgendaGroup is active
    if (rule.isLockOnActive()
        && agendaGroup.isActive()
        && agendaGroup.getAutoFocusActivator() != context) {
      return false;
    }

    item = createAgendaItem(tuple, 0, context, rtn, null, agendaGroup);
    item.setSalience(
        rule.getSalience()
            .getValue(new DefaultKnowledgeHelper(item, workingMemory), rule, workingMemory));

    if (activationsFilter != null && !activationsFilter.accept(item, workingMemory, rtn)) {
      return false;
    }
    item.setQueued(true);
    tuple.increaseActivationCountForEvents();

    ((EventSupport) workingMemory)
        .getAgendaEventSupport()
        .fireActivationCreated(item, workingMemory);
    return true;
  }
コード例 #15
0
ファイル: RuleTest.java プロジェクト: mok89/drools
  @Test
  public void testDateExpires() throws Exception {
    WorkingMemory wm = new KnowledgeBaseImpl("x", null).newStatefulSession();

    final RuleImpl rule = new RuleImpl("myrule");

    assertTrue(rule.isEffective(null, new RuleTerminalNode(), wm));

    final Calendar earlier = Calendar.getInstance();
    earlier.setTimeInMillis(10);

    rule.setDateExpires(earlier);

    assertFalse(rule.isEffective(null, new RuleTerminalNode(), wm));

    final Calendar later = Calendar.getInstance();
    later.setTimeInMillis(later.getTimeInMillis() + 100000000);

    rule.setDateExpires(later);
    assertTrue(rule.isEffective(null, new RuleTerminalNode(), wm));
  }
コード例 #16
0
ファイル: RuleTest.java プロジェクト: mok89/drools
  @Test
  public void testTimeMachine() {
    SessionConfiguration conf = SessionConfiguration.newInstance();
    conf.setClockType(ClockType.PSEUDO_CLOCK);
    WorkingMemory wm = new KnowledgeBaseImpl("x", null).newStatefulSession(conf, null);

    final Calendar future = Calendar.getInstance();
    ((PseudoClockScheduler) wm.getSessionClock()).setStartupTime(future.getTimeInMillis());

    final RuleImpl rule = new RuleImpl("myrule");
    rule.setEnabled(EnabledBoolean.ENABLED_TRUE);
    assertTrue(rule.isEffective(null, new RuleTerminalNode(), wm));

    future.setTimeInMillis(future.getTimeInMillis() + 100000000);
    rule.setDateEffective(future);
    assertFalse(rule.isEffective(null, new RuleTerminalNode(), wm));

    ((PseudoClockScheduler) wm.getSessionClock())
        .advanceTime(1000000000000L, TimeUnit.MILLISECONDS);

    assertTrue(rule.isEffective(null, new RuleTerminalNode(), wm));
  }
コード例 #17
0
 public void removeRule(RuleImpl rule) {
   this.rules.remove(rule.getName());
   this.dialectRuntimeRegistry.removeRule(this, rule);
 }
コード例 #18
0
 /**
  * Add a <code>Rule</code> to this <code>Package</code>.
  *
  * @param rule The rule to add.
  * @throws org.drools.core.rule.DuplicateRuleNameException If the <code>Rule</code> attempting to
  *     be added has the same name as another previously added <code>Rule</code>.
  * @throws org.drools.core.rule.InvalidRuleException If the <code>Rule</code> is not valid.
  */
 public void addRule(RuleImpl rule) {
   this.rules.put(rule.getName(), rule);
 }
コード例 #19
0
  /* (non-Javadoc)
   * @see junit.framework.TestCase#setUp()
   */
  @Before
  public void setUp() throws Exception {
    kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    listener1 = new TestRuleBaseListener("(listener-1) ");
    listener2 = new TestRuleBaseListener("(listener-2) ");
    kBase.addEventListener(listener1);
    kBase.addEventListener(listener2);

    final RuleImpl rule1 = new RuleImpl("test1");
    final ClassObjectType cheeseObjectType = new ClassObjectType(Cheese.class);
    final Pattern pattern = new Pattern(0, cheeseObjectType);

    ClassFieldAccessorStore store = new ClassFieldAccessorStore();
    store.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    store.setEagerWire(true);

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

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

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

    pattern.addConstraint(constraint);
    rule1.addPattern(pattern);

    rule1.setConsequence(
        new Consequence() {
          private static final long serialVersionUID = 510l;

          public void evaluate(
              final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory)
              throws Exception {}

          public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {}

          public void writeExternal(ObjectOutput out) throws IOException {}

          public String getName() {
            return "default";
          }
        });

    final RuleImpl rule2 = new RuleImpl("test2");
    final ClassObjectType cheeseObjectType2 = new ClassObjectType(Cheese.class);
    final Pattern pattern2 = new Pattern(0, cheeseObjectType2);

    final FieldValue field2 = FieldFactory.getInstance().getFieldValue("stilton");

    final MvelConstraint constraint2 =
        new MvelConstraintTestUtil("type == \"stilton\"", field, extractor);

    pattern2.addConstraint(constraint2);
    rule2.addPattern(pattern2);

    rule2.setConsequence(
        new Consequence() {
          private static final long serialVersionUID = 510l;

          public void evaluate(
              final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory)
              throws Exception {}

          public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {}

          public void writeExternal(ObjectOutput out) throws IOException {}

          public String getName() {
            return "default";
          }
        });

    pkg = new KnowledgePackageImpl("org.drools.test1");
    pkg.addRule(rule1);
    pkg.addRule(rule2);
  }
コード例 #20
0
ファイル: ReteAgenda.java プロジェクト: chearius/drools
  public boolean createActivation(
      final LeftTuple tuple,
      final PropagationContext context,
      final InternalWorkingMemory workingMemory,
      final TerminalNode rtn) {
    // First process control rules
    // Control rules do increase ActivationCountForEvent and agenda ActivateActivations, they do not
    // currently fire events
    // ControlRules for now re-use the same PropagationContext
    if (rtn.isFireDirect()) {
      // Fire RunLevel == 0 straight away. agenda-groups, rule-flow groups, salience are ignored
      AgendaItem item = createAgendaItem(tuple, 0, context, rtn, null, null);
      tuple.setObject(item);
      if (activationsFilter != null && !activationsFilter.accept(item, workingMemory, rtn)) {
        return false;
      }

      item.setQueued(true);
      tuple.increaseActivationCountForEvents();
      fireActivation(item); // Control rules fire straight away.
      return true;
    }

    final RuleImpl rule = rtn.getRule();
    AgendaItem item;
    final Timer timer = rule.getTimer();
    InternalAgendaGroup agendaGroup = (InternalAgendaGroup) getAgendaGroup(rule.getAgendaGroup());
    if (timer != null) {
      item = createScheduledAgendaItem(tuple, context, rtn, agendaGroup);
    } else {
      if (rule.getCalendars() != null) {
        // for normal activations check for Calendar inclusion here, scheduled activations check on
        // each trigger point
        long timestamp = workingMemory.getSessionClock().getCurrentTime();
        for (String cal : rule.getCalendars()) {
          if (!workingMemory.getCalendars().get(cal).isTimeIncluded(timestamp)) {
            return false;
          }
        }
      }

      if (rule.isLockOnActive()
          && agendaGroup.isActive()
          && agendaGroup.getAutoFocusActivator() != context) {
        // do not add the activation if the rule is "lock-on-active" and the AgendaGroup is active
        if (tuple.getObject() == null) {
          tuple.setObject(
              Boolean
                  .TRUE); // this is so we can do a check with a bit more intent than a null check
                          // on modify
        }
        return false;
      }

      item = createAgendaItem(tuple, 0, context, rtn, null, agendaGroup);
      item.setSalience(
          rule.getSalience()
              .getValue(new DefaultKnowledgeHelper(item, workingMemory), rule, workingMemory));
    }

    if (activationsFilter != null && !activationsFilter.accept(item, workingMemory, rtn)) {
      return false;
    }
    item.setQueued(true);
    tuple.increaseActivationCountForEvents();

    ((EventSupport) workingMemory)
        .getAgendaEventSupport()
        .fireActivationCreated(item, workingMemory);
    return true;
  }