/**
   * Tests the assertion of objects into LeftInputAdapterNode
   *
   * @throws Exception
   */
  @Test
  public void testAssertObjectWithoutMemory() throws Exception {
    PropagationContextFactory pctxFactory =
        kBase.getConfiguration().getComponentFactory().getPropagationContextFactory();
    final PropagationContext pcontext =
        pctxFactory.createPropagationContext(0, PropagationContext.INSERTION, null, null, null);

    BuildContext context = new BuildContext(kBase, kBase.getReteooBuilder().getIdGenerator());
    final EntryPointNode entryPoint = new EntryPointNode(-1, kBase.getRete(), context);
    entryPoint.attach(context);

    final ObjectTypeNode objectTypeNode =
        new ObjectTypeNode(0, entryPoint, new ClassObjectType(Object.class), context);

    objectTypeNode.attach(context);

    final LeftInputAdapterNode liaNode = new LeftInputAdapterNode(23, objectTypeNode, buildContext);
    liaNode.attach(context);

    final StatefulKnowledgeSessionImpl workingMemory = new StatefulKnowledgeSessionImpl(1L, kBase);

    final MockLeftTupleSink sink = new MockLeftTupleSink();
    liaNode.addTupleSink(sink);

    final Object string1 = "cheese";

    // assert object
    final DefaultFactHandle f0 = (DefaultFactHandle) workingMemory.insert(string1);
    liaNode.assertObject(f0, pcontext, workingMemory);

    final List asserted = sink.getAsserted();
    assertLength(1, asserted);
    final LeftTuple tuple0 = (LeftTuple) ((Object[]) asserted.get(0))[0];
    assertSame(string1, workingMemory.getObject(tuple0.get(0)));
  }
Beispiel #2
0
  @Test
  public void testEqualsObject() {
    final LeftTupleSource ts = new MockTupleSource(1);
    final ObjectSource os = new MockObjectSource(2);

    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    BuildContext buildContext = new BuildContext(kBase, kBase.getReteooBuilder().getIdGenerator());

    final BetaNode j1 = new JoinNode(1, ts, os, EmptyBetaConstraints.getInstance(), buildContext);
    final BetaNode j2 = new JoinNode(2, ts, os, EmptyBetaConstraints.getInstance(), buildContext);
    final BetaNode n1 = new NotNode(3, ts, os, EmptyBetaConstraints.getInstance(), buildContext);
    final BetaNode n2 = new NotNode(4, ts, os, EmptyBetaConstraints.getInstance(), buildContext);

    assertEquals(j1, j1);
    assertEquals(j2, j2);
    assertEquals(j1, j2);
    assertEquals(n1, n1);
    assertEquals(n2, n2);
    assertEquals(n1, n2);

    assertFalse(j1.equals(n1));
    assertFalse(j1.equals(n2));
    assertFalse(n1.equals(j1));
    assertFalse(n1.equals(j2));
  }
Beispiel #3
0
  public ClassObjectTypeConf(
      final EntryPointId entryPoint, final Class<?> clazz, final InternalKnowledgeBase kBase) {
    this.cls =
        (Activation.class.isAssignableFrom(clazz))
            ? ClassObjectType.Match_ObjectType.getClassType()
            : clazz;
    this.kBase = kBase;
    this.entryPoint = entryPoint;

    this.typeDecl = kBase.getTypeDeclaration(clazz);
    isEvent = typeDecl != null && typeDecl.getRole() == Role.Type.EVENT;
    if (isEvent) {
      expirationOffset = typeDecl.getExpirationOffset();
    }

    isTrait = determineTraitStatus();

    this.objectType =
        kBase
            .getClassFieldAccessorCache()
            .getClassObjectType(new ClassObjectType(clazz, isEvent), false);

    this.concreteObjectTypeNode = kBase.getRete().getObjectTypeNodes(entryPoint).get(objectType);

    this.supportsPropertyListeners = checkPropertyListenerSupport(clazz);

    Traitable ttbl = cls.getAnnotation(Traitable.class);
    this.traitTmsEnabled = ttbl != null && ttbl.logical();
  }
Beispiel #4
0
  /**
   * Construct.
   *
   * @param kBase The <code>InternalKnowledgeBase</code> of this agenda.
   * @param initMain Flag to initialize the MAIN agenda group
   */
  public ReteAgenda(InternalKnowledgeBase kBase, boolean initMain) {

    this.agendaGroups = new HashMap<String, InternalAgendaGroup>();
    this.activationGroups = new HashMap<String, InternalActivationGroup>();
    this.focusStack = new LinkedList<AgendaGroup>();
    this.scheduledActivations = new org.drools.core.util.LinkedList<ScheduledAgendaItem>();
    this.agendaGroupFactory = kBase.getConfiguration().getAgendaGroupFactory();

    if (initMain) {
      // MAIN should always be the first AgendaGroup and can never be
      // removed
      this.main = agendaGroupFactory.createAgendaGroup(AgendaGroup.MAIN, kBase);

      this.agendaGroups.put(AgendaGroup.MAIN, this.main);

      this.focusStack.add(this.main);
    }
    eager = new LinkedList<RuleAgendaItem>();

    Object object =
        ClassUtils.instantiateObject(
            kBase.getConfiguration().getConsequenceExceptionHandler(),
            kBase.getConfiguration().getClassLoader());
    if (object instanceof ConsequenceExceptionHandler) {
      this.legacyConsequenceExceptionHandler = (ConsequenceExceptionHandler) object;
    } else {
      this.consequenceExceptionHandler =
          (org.kie.api.runtime.rule.ConsequenceExceptionHandler) object;
    }

    this.declarativeAgenda = kBase.getConfiguration().isDeclarativeAgenda();
  }
Beispiel #5
0
  @Test
  public void testCancelNonRegisteredWorkItemHandler() {
    String processId = "org.drools.actions";
    String workName = "Unnexistent Task";
    RuleFlowProcess process = getWorkItemProcess(processId, workName);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    ((AbstractRuleBase) ((InternalKnowledgeBase) kbase).getRuleBase()).addProcess(process);
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    ksession.getWorkItemManager().registerWorkItemHandler(workName, new DoNothingWorkItemHandler());

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("UserName", "John Doe");
    parameters.put("Person", new Person("John Doe"));

    ProcessInstance processInstance = ksession.startProcess("org.drools.actions", parameters);
    long processInstanceId = processInstance.getId();
    Assert.assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    ksession.getWorkItemManager().registerWorkItemHandler(workName, null);

    try {
      ksession.abortProcessInstance(processInstanceId);
      Assert.fail("should fail if WorkItemHandler for" + workName + "is not registered");
    } catch (WorkItemHandlerNotFoundException wihnfe) {

    }

    Assert.assertEquals(ProcessInstance.STATE_ABORTED, processInstance.getState());
  }
  private KieBase createKieBase(
      KieBaseModelImpl kBaseModel,
      KieProject kieProject,
      ResultsImpl messages,
      KieBaseConfiguration conf) {
    ClassLoader cl = kieProject.getClassLoader();
    InternalKieModule kModule = kieProject.getKieModuleForKBase(kBaseModel.getName());

    Collection<KnowledgePackage> pkgs =
        kModule.getKnowledgePackagesForKieBase(kBaseModel.getName());

    if (pkgs == null) {
      KnowledgeBuilder kbuilder = buildKnowledgePackages(kBaseModel, kieProject, messages);
      if (kbuilder.hasErrors()) {
        // Messages already populated by the buildKnowlegePackages
        return null;
      }
    }

    // if we get to here, then we know the pkgs is now cached
    pkgs = kModule.getKnowledgePackagesForKieBase(kBaseModel.getName());

    if (kBaseModel.getEventProcessingMode() == EventProcessingOption.CLOUD
        && (conf == null
            || conf.getOption(EventProcessingOption.class) == EventProcessingOption.CLOUD)) {
      for (KnowledgePackage kpkg : pkgs) {
        if (((KnowledgePackageImpl) kpkg).needsStreamMode()) {
          throw new RuntimeException(
              "The requested KieBase \""
                  + kBaseModel.getName()
                  + "\" has been set to run in CLOUD mode but requires features only available in STREAM mode");
        }
      }
    }

    if (conf == null) {
      conf = getKnowledgeBaseConfiguration(kBaseModel, cl);
    } else if (conf instanceof RuleBaseConfiguration) {
      ((RuleBaseConfiguration) conf).setClassLoader(cl);
    }
    InternalKnowledgeBase kBase =
        (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase(conf);

    kBase.addKnowledgePackages(pkgs);
    return kBase;
  }
  @Before
  public void setUp() throws Exception {
    store.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    store.setEagerWire(true);
    this.kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();

    this.buildContext = new BuildContext(kBase, kBase.getReteooBuilder().getIdGenerator());
  }
Beispiel #8
0
  public Rete(InternalKnowledgeBase kBase) {
    super(
        0,
        RuleBasePartitionId.MAIN_PARTITION,
        kBase != null && kBase.getConfiguration().isMultithreadEvaluation());
    this.entryPoints = Collections.synchronizedMap(new HashMap<EntryPointId, EntryPointNode>());
    this.kBase = kBase;

    hashcode = calculateHashCode();
  }
  private InternalFactHandle createEventFactHandle(
      StatefulKnowledgeSessionImpl wm, InternalKnowledgeBase kBase) {
    // EntryPointNode
    Rete rete = kBase.getRete();

    NodeFactory nFacotry = kBase.getConfiguration().getComponentFactory().getNodeFactoryService();

    RuleBasePartitionId partionId = RuleBasePartitionId.MAIN_PARTITION;
    EntryPointNode entryPointNode =
        nFacotry.buildEntryPointNode(
            1, partionId, false, (ObjectSource) rete, EntryPointId.DEFAULT);
    InternalWorkingMemoryEntryPoint wmEntryPoint =
        new NamedEntryPoint(EntryPointId.DEFAULT, entryPointNode, wm);

    EventFactHandle factHandle =
        new EventFactHandle(1, (Object) new Person(), 0, (new Date()).getTime(), 0, wmEntryPoint);

    return factHandle;
  }
Beispiel #10
0
  @Before
  public void setUp() throws Exception {
    store.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    store.setEagerWire(true);

    this.kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    buildContext = new BuildContext(kBase, new ReteooBuilder.IdGenerator());
    pctxFactory = kBase.getConfiguration().getComponentFactory().getPropagationContextFactory();
  }
  @Test
  public void testLeftInputAdapterNode() {
    BuildContext context = new BuildContext(kBase, kBase.getReteooBuilder().getIdGenerator());
    final EntryPointNode entryPoint = new EntryPointNode(-1, kBase.getRete(), context);
    entryPoint.attach(context);

    final ObjectTypeNode objectTypeNode =
        new ObjectTypeNode(0, entryPoint, new ClassObjectType(Object.class), context);

    objectTypeNode.attach(context);

    final LeftInputAdapterNode liaNode = new LeftInputAdapterNode(23, objectTypeNode, buildContext);

    assertEquals(23, liaNode.getId());

    assertEquals(0, objectTypeNode.getSinkPropagator().getSinks().length);
    liaNode.attach(context);
    assertEquals(1, objectTypeNode.getSinkPropagator().getSinks().length);
  }
Beispiel #12
0
 @SuppressWarnings("unchecked")
 public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
   entryPoints = (Map<EntryPointId, EntryPointNode>) in.readObject();
   kBase = ((DroolsObjectInputStream) in).getKnowledgeBase();
   for (Map.Entry<EntryPointId, EntryPointNode> entry : entryPoints.entrySet()) {
     EntryPointNode node = entry.getValue();
     if (node.getEntryPoint() == null) node.setEntryPoint(entry.getKey());
     kBase.registerAddedEntryNodeCache(node);
   }
   super.readExternal(in);
 }
Beispiel #13
0
  public ClassObjectTypeConf(
      final EntryPointId entryPoint, final Class<?> clazz, final InternalKnowledgeBase kBase) {
    this.cls =
        (Activation.class.isAssignableFrom(clazz))
            ? ClassObjectType.Match_ObjectType.getClassType()
            : clazz;
    this.kBase = kBase;
    this.entryPoint = entryPoint;
    this.typeDecl = kBase.getTypeDeclaration(clazz);
    isEvent = typeDecl != null && typeDecl.getRole() == TypeDeclaration.Role.EVENT;
    isTrait = determineTraitStatus();

    ObjectType objectType =
        kBase.getClassFieldAccessorCache().getClassObjectType(new ClassObjectType(clazz, isEvent));

    this.concreteObjectTypeNode = kBase.getRete().getObjectTypeNodes(entryPoint).get(objectType);
    if (this.concreteObjectTypeNode == null) {
      BuildContext context = new BuildContext(kBase, kBase.getReteooBuilder().getIdGenerator());
      context.setCurrentEntryPoint(entryPoint);
      if (DroolsQuery.class == clazz) {
        context.setTupleMemoryEnabled(false);
        context.setObjectTypeNodeMemoryEnabled(false);
      } else if (context.getKnowledgeBase().getConfiguration().isSequential()) {
        // We are in sequential mode, so no nodes should have memory
        //                context.setTupleMemoryEnabled( false );
        //                context.setObjectTypeNodeMemoryEnabled( false );
        context.setTupleMemoryEnabled(true);
        context.setObjectTypeNodeMemoryEnabled(true);
      } else {
        context.setTupleMemoryEnabled(true);
        context.setObjectTypeNodeMemoryEnabled(true);
      }
      // there must exist an ObjectTypeNode for this concrete class
      this.concreteObjectTypeNode = PatternBuilder.attachObjectTypeNode(context, objectType);
    }

    this.supportsPropertyListeners = checkPropertyListenerSupport(clazz);

    Traitable ttbl = cls.getAnnotation(Traitable.class);
    this.traitTmsEnabled = ttbl != null && ttbl.logical();
  }
Beispiel #14
0
  private ObjectTypeNode[] getMatchingObjectTypes(final Class<?> clazz) {
    final List<ObjectTypeNode> cache = new ArrayList<ObjectTypeNode>();

    for (ObjectTypeNode node : kBase.getRete().getObjectTypeNodes(this.entryPoint).values()) {
      if (clazz == DroolsQuery.class) {
        // for query objects only add direct matches
        if (((ClassObjectType) node.getObjectType()).getClassType() == clazz) {
          cache.add(node);
        }
      } else if (node.isAssignableFrom(new ClassObjectType(clazz))) {
        cache.add(node);
      }
    }

    Collections.sort(cache, OBJECT_TYPE_NODE_COMPARATOR);
    return cache.toArray(new ObjectTypeNode[cache.size()]);
  }
  private void updateKBase(
      InternalKnowledgeBase kBase,
      InternalKieModule currentKM,
      ReleaseId newReleaseId,
      InternalKieModule newKM,
      KieJarChangeSet cs,
      List<String> modifiedClasses,
      List<String> dslFiles,
      ResultsImpl results,
      KieBaseModel kieBaseModel) {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(kBase);
    KnowledgeBuilderImpl pkgbuilder = (KnowledgeBuilderImpl) kbuilder;
    CompositeKnowledgeBuilder ckbuilder = kbuilder.batch();

    boolean shouldRebuild =
        applyResourceChanges(
            currentKM, newKM, cs, modifiedClasses, kBase, kieBaseModel, pkgbuilder, ckbuilder);
    // remove resources first
    for (ResourceChangeSet rcs : cs.getChanges().values()) {
      if (rcs.getChangeType() == ChangeType.REMOVED) {
        String resourceName = rcs.getResourceName();
        if (!resourceName.endsWith(".properties")
            && isFileInKBase(newKM, kieBaseModel, resourceName)) {
          pkgbuilder.removeObjectsGeneratedFromResource(currentKM.getResource(resourceName));
        }
      }
    }

    if (shouldRebuild) {
      // readd unchanged dsl files to the kbuilder
      for (String dslFile : dslFiles) {
        if (isFileInKBase(newKM, kieBaseModel, dslFile)) {
          newKM.addResourceToCompiler(ckbuilder, kieBaseModel, dslFile);
        }
      }
      rebuildAll(
          newReleaseId, results, newKM, modifiedClasses, kieBaseModel, pkgbuilder, ckbuilder);
    }

    for (StatefulKnowledgeSession session : kBase.getStatefulKnowledgeSessions()) {
      ((InternalWorkingMemory) session).notifyHalt();
    }
  }
Beispiel #16
0
  @Test
  public void testReachNonRegisteredWorkItemHandler() {
    String processId = "org.drools.actions";
    String workName = "Unnexistent Task";
    RuleFlowProcess process = getWorkItemProcess(processId, workName);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    ((AbstractRuleBase) ((InternalKnowledgeBase) kbase).getRuleBase()).addProcess(process);
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("UserName", "John Doe");
    parameters.put("Person", new Person("John Doe"));

    ProcessInstance processInstance = null;
    try {
      processInstance = ksession.startProcess("org.drools.actions", parameters);
      Assert.fail("should fail if WorkItemHandler for" + workName + "is not registered");
    } catch (Throwable e) {

    }
    Assert.assertNull(processInstance);
  }
  /**
   * 加载规则package
   *
   * @param userRule
   */
  private void loadPackage(UserRule userRule) {
    if (kBase.getKiePackage("com.camel.drools.expert.sample." + userRule.getUserCode()) != null) {
      return;
    }

    final KnowledgeBuilderImpl builder = new KnowledgeBuilderImpl();
    File file =
        new File(
            KieSpringBasicService.class.getResource("/").getPath().toString()
                + drlDirPath
                + userRule.getUserCode()
                + ".drl");
    try {
      String drl = FileUtils.readFileToString(file);
      builder.addPackageFromDrl(new StringReader(drl));
      if (builder.hasErrors()) {
        System.out.println("[ERROR: Parsing drl error: " + builder.getErrors());
      }
    } catch (DroolsParserException | IOException e) {
      e.printStackTrace();
    }
    ((InternalKnowledgeBase) kBase).addPackage(builder.getPackage());
  }
  @Test
  public void testQueryTerminalNode() {
    final ClassObjectType queryObjectType = new ClassObjectType(DroolsQuery.class);
    final ObjectTypeNode queryObjectTypeNode =
        new ObjectTypeNode(
            this.buildContext.getNextId(), this.entryPoint, queryObjectType, buildContext);
    queryObjectTypeNode.attach(buildContext);

    ClassFieldReader extractor = store.getReader(DroolsQuery.class, "name");

    MvelConstraint constraint =
        new MvelConstraintTestUtil(
            "name == \"query-1\"", FieldFactory.getInstance().getFieldValue("query-1"), extractor);

    final QueryImpl query = new QueryImpl("query-1");
    buildContext.setRule(query);
    AlphaNode alphaNode =
        new AlphaNode(this.buildContext.getNextId(), constraint, queryObjectTypeNode, buildContext);
    alphaNode.attach(buildContext);

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

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

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

    constraint =
        new MvelConstraintTestUtil(
            "type == \"stilton\"", FieldFactory.getInstance().getFieldValue("stilton"), extractor);

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

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

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

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

    queryNode.attach(buildContext);

    final KnowledgePackageImpl pkg = new KnowledgePackageImpl("com.drools.test");
    pkg.addRule(query);
    ((KnowledgeBaseImpl) kBase).addPackages(Arrays.asList(new InternalKnowledgePackage[] {pkg}));

    KieSession kSession = kBase.newKieSession();
    QueryResults results = kSession.getQueryResults("query-1");

    assertEquals(0, results.size());

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

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

    assertEquals(1, results.size());

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

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

    assertEquals(1, results.size());

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

    final FactHandle handle2 = kSession.insert(stilton2);

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

    assertEquals(2, results.size());

    /**
     * QueryResultsRow result = results.get( 0 ); assertEquals( 1, result.size() ); assertEquals(
     * stilton1, result.get( 0 ) );
     *
     * <p>result = results.get( 1 ); assertEquals( 1, result.size() ); assertEquals( stilton2,
     * result.get( 0 ) );
     */
    int i = 0;
    for (final Iterator<QueryResultsRow> it = results.iterator(); it.hasNext(); ) {
      QueryResultsRow resultRow = it.next();
      if (i == 1) {
        //                assertSame( stilton2, result.g( 0 ) );
      } else {
        //                assertSame( stilton1, result.get( 0 ) );
      }
      i++;
    }

    kSession.delete(handle1);
    results = kSession.getQueryResults("query-1");

    assertEquals(1, results.size());

    kSession.delete(handle2);
    results = kSession.getQueryResults("query-1");

    assertEquals(0, results.size());
  }
Beispiel #19
0
 public ObjectTypeNode getConcreteObjectTypeNode() {
   if (concreteObjectTypeNode == null) {
     concreteObjectTypeNode = kBase.getRete().getObjectTypeNodes(entryPoint).get(objectType);
   }
   return concreteObjectTypeNode;
 }
Beispiel #20
0
 public void removeObjectSink(final ObjectSink objectSink) {
   final EntryPointNode node = (EntryPointNode) objectSink;
   entryPoints.remove(node.getEntryPoint());
   kBase.registeRremovedEntryNodeCache(node);
 }
Beispiel #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 EntryPointNode node = (EntryPointNode) objectSink;
   entryPoints.put(node.getEntryPoint(), node);
   kBase.registerAddedEntryNodeCache(node);
 }
  private Results update(final InternalKieModule currentKM, final ReleaseId newReleaseId) {
    final InternalKieModule newKM = (InternalKieModule) kr.getKieModule(newReleaseId);
    ChangeSetBuilder csb = new ChangeSetBuilder();
    final KieJarChangeSet cs = csb.build(currentKM, newKM);

    final List<String> modifiedClasses = getModifiedClasses(cs);
    final List<String> dslFiles = getUnchangedDslFiles(newKM, cs);

    ((KieModuleKieProject) kProject).updateToModule(newKM);

    final ResultsImpl results = new ResultsImpl();

    List<String> kbasesToRemove = new ArrayList<String>();
    for (Entry<String, KieBase> kBaseEntry : kBases.entrySet()) {
      String kbaseName = kBaseEntry.getKey();
      final KieBaseModel kieBaseModel = kProject.getKieBaseModel(kbaseName);
      // if a kbase no longer exists, just remove it from the cache
      if (kieBaseModel == null) {
        // have to save for later removal to avoid iteration errors
        kbasesToRemove.add(kbaseName);
      } else {
        final InternalKnowledgeBase kBase = (InternalKnowledgeBase) kBaseEntry.getValue();
        boolean locked = kBase.tryLock();
        if (locked) {
          try {
            updateKBase(
                kBase,
                currentKM,
                newReleaseId,
                newKM,
                cs,
                modifiedClasses,
                dslFiles,
                results,
                kieBaseModel);
          } finally {
            kBase.unlock();
          }
        } else {
          kBase.enqueueModification(
              new Runnable() {
                @Override
                public void run() {
                  updateKBase(
                      kBase,
                      currentKM,
                      newReleaseId,
                      newKM,
                      cs,
                      modifiedClasses,
                      dslFiles,
                      results,
                      kieBaseModel);
                }
              });
        }
      }
    }

    for (String kbaseToRemove : kbasesToRemove) {
      kBases.remove(kbaseToRemove);
    }

    for (Iterator<Entry<String, KieSession>> it = this.kSessions.entrySet().iterator();
        it.hasNext(); ) {
      Entry<String, KieSession> ksession = it.next();
      if (kProject.getKieSessionModel(ksession.getKey()) == null) {
        // remove sessions that no longer exist
        it.remove();
      }
    }

    for (Iterator<Entry<String, StatelessKieSession>> it =
            this.statelessKSessions.entrySet().iterator();
        it.hasNext(); ) {
      Entry<String, StatelessKieSession> ksession = it.next();
      if (kProject.getKieSessionModel(ksession.getKey()) == null) {
        // remove sessions that no longer exist
        it.remove();
      }
    }

    return results;
  }
  /* (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);
  }
  @Test
  public void testImperativeCodeError() throws Exception {
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("pkg1");
    final RuleDescr ruleDescr = new RuleDescr("rule 1");
    ruleDescr.setConsequence("if (cheese.price == 10) { cheese.price = 5; }");

    Properties properties = new Properties();
    properties.setProperty("drools.dialect.default", "mvel");
    KnowledgeBuilderConfigurationImpl cfg1 = new KnowledgeBuilderConfigurationImpl(properties);

    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg, cfg1);
    final KnowledgeBuilderConfigurationImpl conf = pkgBuilder.getBuilderConfiguration();
    PackageRegistry pkgRegistry = pkgBuilder.getPackageRegistry(pkg.getName());
    DialectCompiletimeRegistry dialectRegistry =
        pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    MVELDialect mvelDialect = (MVELDialect) dialectRegistry.getDialect(pkgRegistry.getDialect());

    final InstrumentedBuildContent context =
        new InstrumentedBuildContent(pkgBuilder, ruleDescr, dialectRegistry, pkg, mvelDialect);

    final InstrumentedDeclarationScopeResolver declarationResolver =
        new InstrumentedDeclarationScopeResolver();

    final ObjectType cheeseObjeectType = new ClassObjectType(Cheese.class);

    final Pattern pattern = new Pattern(0, cheeseObjeectType);

    final PatternExtractor extractor = new PatternExtractor(cheeseObjeectType);

    final Declaration declaration = new Declaration("cheese", extractor, pattern);
    final Map<String, Declaration> map = new HashMap<String, Declaration>();
    map.put("cheese", declaration);
    declarationResolver.setDeclarations(map);
    context.setDeclarationResolver(declarationResolver);

    final MVELConsequenceBuilder builder = new MVELConsequenceBuilder();
    builder.build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);

    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl ksession =
        (StatefulKnowledgeSessionImpl) kBase.newStatefulKnowledgeSession();

    final Cheese cheddar = new Cheese("cheddar", 10);
    final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar);
    final LeftTupleImpl tuple = new LeftTupleImpl(f0, null, true);

    final AgendaItem item = new AgendaItemImpl(0, tuple, 10, null, null, null);
    final DefaultKnowledgeHelper kbHelper = new DefaultKnowledgeHelper(ksession);
    kbHelper.setActivation(item);
    try {
      ((MVELConsequence) context.getRule().getConsequence())
          .compile(
              (MVELDialectRuntimeData)
                  pkgBuilder
                      .getPackageRegistry(pkg.getName())
                      .getDialectRuntimeRegistry()
                      .getDialectData("mvel"));
      context.getRule().getConsequence().evaluate(kbHelper, ksession);
      fail("should throw an exception, as 'if' is not allowed");
    } catch (Exception e) {
    }

    assertEquals(10, cheddar.getPrice());
  }
  @Test
  public void testSimpleExpression() throws Exception {
    PackageDescr pkgDescr = new PackageDescr("pkg1");
    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl();
    pkgBuilder.addPackage(pkgDescr);

    InternalKnowledgePackage pkg = pkgBuilder.getPackageRegistry("pkg1").getPackage();
    final RuleDescr ruleDescr = new RuleDescr("rule 1");
    ruleDescr.setNamespace("pkg1");
    ruleDescr.setConsequence("modify (cheese) {price = 5 };\nretract (cheese)");

    DialectCompiletimeRegistry dialectRegistry =
        pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();

    MVELDialect mvelDialect = (MVELDialect) dialectRegistry.getDialect("mvel");

    final InstrumentedBuildContent context =
        new InstrumentedBuildContent(pkgBuilder, ruleDescr, dialectRegistry, pkg, mvelDialect);

    final InstrumentedDeclarationScopeResolver declarationResolver =
        new InstrumentedDeclarationScopeResolver();

    final ObjectType cheeseObjeectType = new ClassObjectType(Cheese.class);

    final Pattern pattern = new Pattern(0, cheeseObjeectType, "cheese");

    final GroupElement subrule = new GroupElement(GroupElement.AND);
    subrule.addChild(pattern);
    final Map<String, Declaration> map = new HashMap<String, Declaration>();
    map.put("cheese", pattern.getDeclaration());
    declarationResolver.setDeclarations(map);
    context.setDeclarationResolver(declarationResolver);

    final MVELConsequenceBuilder builder = new MVELConsequenceBuilder();
    builder.build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);

    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();

    PropagationContextFactory pctxFactory =
        kBase.getConfiguration().getComponentFactory().getPropagationContextFactory();
    kBase.addPackage(pkg);

    StatefulKnowledgeSessionImpl ksession =
        (StatefulKnowledgeSessionImpl) kBase.newStatefulKnowledgeSession();

    final Cheese cheddar = new Cheese("cheddar", 10);
    final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar);
    final LeftTupleImpl tuple = new LeftTupleImpl(f0, null, true);
    f0.removeLeftTuple(tuple);

    final AgendaItem item =
        new AgendaItemImpl(
            0,
            tuple,
            10,
            pctxFactory.createPropagationContext(1, 1, null, tuple, null),
            new RuleTerminalNode(
                0,
                new CompositeObjectSinkAdapterTest.MockBetaNode(),
                context.getRule(),
                subrule,
                0,
                new BuildContext(kBase, null)),
            null);
    final DefaultKnowledgeHelper kbHelper = new DefaultKnowledgeHelper(ksession);
    kbHelper.setActivation(item);
    ((MVELConsequence) context.getRule().getConsequence())
        .compile(
            (MVELDialectRuntimeData)
                pkgBuilder
                    .getPackageRegistry(pkg.getName())
                    .getDialectRuntimeRegistry()
                    .getDialectData("mvel"));
    context.getRule().getConsequence().evaluate(kbHelper, ksession);

    assertEquals(5, cheddar.getPrice());
  }
 @Before
 public void setUp() throws Exception {
   this.kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
   this.buildContext = new BuildContext(kBase, kBase.getReteooBuilder().getIdGenerator());
 }