Example #1
0
  /**
   * This method creates a stateful knowledge session per Drools event processor.
   *
   * @return The stateful knowledge session
   */
  private KieSession createSession() {
    KieSession ret = null;

    synchronized (SESSIONS) {
      ret = SESSIONS.get(getRuleName());

      if (ret == null) {
        KieBase kbase = loadRuleBase();

        if (kbase != null) {
          ret = kbase.newKieSession();

          if (ret != null) {
            ret.setGlobal("epc", _context);
            ret.fireAllRules();

            SESSIONS.put(getRuleName(), ret);
          } else {
            System.out.println("The kieSession is null!!!");
          }
        }
      }
    }

    return (ret);
  }
Example #2
0
  @Test
  public void testSignalStartDynamic() throws Exception {

    KieBase kbase = createKnowledgeBase("BPMN2-SignalStart.bpmn2");
    ksession = createKnowledgeSession(kbase);
    // create KieContainer after session was created to make sure no runtime data
    // will be used during serialization (deep clone)
    KieServices ks = KieServices.Factory.get();
    KieRepository kr = ks.getRepository();
    KieContainer kContainer = ks.newKieContainer(kr.getDefaultReleaseId());
    kContainer.getKieBase();

    final List<Long> list = new ArrayList<Long>();
    ksession.addEventListener(
        new DefaultProcessEventListener() {
          public void afterProcessStarted(ProcessStartedEvent event) {
            logger.info("{}", event.getProcessInstance().getId());
            list.add(event.getProcessInstance().getId());
          }
        });
    ksession.signalEvent("MySignal", "NewValue");
    Thread.sleep(500);
    assertEquals(1, getNumberOfProcessInstances("Minimal"));
    // now remove the process from kbase to make sure runtime based listeners are removed from
    // signal manager
    kbase.removeProcess("Minimal");
    ksession.signalEvent("MySignal", "NewValue");
    Thread.sleep(500);
    // must be still one as the process was removed
    assertEquals(1, getNumberOfProcessInstances("Minimal"));
  }
  @Override
  public void start(BundleContext context) throws Exception {

    KieServices ks = KieServices.Factory.get();
    ks.newKieClasspathContainer(getClass().getClassLoader());
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    KieBase kbase = createKieBase();

    ksession = kbase.newKieSession();
    System.out.println("KieSession created.");

    for (int i = 0; i < 10; i++) {
      // Create a Cheese
      Cheese aCheese = EntityHelper.createCheese();
      ksession.insert(aCheese);

      // Fire the rules
      ksession.fireAllRules();

      // Check Cheese Price
      EntityHelper.cheesePrice(aCheese);
    }

    System.out.println("Cheese added and rules fired.");
  }
  public StatelessKieSession newStatelessKieSession(
      String kSessionName, KieSessionConfiguration conf) {
    KieSessionModelImpl kSessionModel =
        (KieSessionModelImpl) kProject.getKieSessionModel(kSessionName);
    if (kSessionModel == null) {
      log.error("Unknown KieSession name: " + kSessionName);
      return null;
    }
    if (kSessionModel.getType() == KieSessionModel.KieSessionType.STATEFUL) {
      throw new RuntimeException(
          "Trying to create a stateless KieSession from a stateful KieSessionModel: "
              + kSessionName);
    }
    KieBase kBase = getKieBase(kSessionModel.getKieBaseModel().getName());
    if (kBase == null) {
      log.error("Unknown KieBase name: " + kSessionModel.getKieBaseModel().getName());
      return null;
    }

    StatelessKieSession statelessKieSession =
        kBase.newStatelessKieSession(
            conf != null ? conf : getKnowledgeSessionConfiguration(kSessionModel));
    wireListnersAndWIHs(kSessionModel, statelessKieSession);
    registerLoggers(kSessionModel, statelessKieSession);
    statelessKSessions.put(kSessionName, statelessKieSession);
    return statelessKieSession;
  }
  protected KieSession createKnowledgeSession(String processFile) throws Exception {
    KieServices ks = KieServices.Factory.get();
    KieRepository kr = ks.getRepository();
    KieFileSystem kfs = ks.newKieFileSystem();
    if (processFile != null) {
      Resource process = ResourceFactory.newClassPathResource(processFile);
      kfs.write(process);
    }

    KieBuilder kb = ks.newKieBuilder(kfs);
    kb.buildAll();

    if (kb.getResults().hasMessages(Level.ERROR)) {
      throw new RuntimeException("Build Errors:\n" + kb.getResults().toString());
    }

    KieContainer kContainer = ks.newKieContainer(kr.getDefaultReleaseId());
    KieBase kbase = kContainer.getKieBase();

    Environment env = EnvironmentFactory.newEnvironment();

    Properties defaultProps = new Properties();
    defaultProps.setProperty(
        "drools.processSignalManagerFactory", DefaultSignalManagerFactory.class.getName());
    defaultProps.setProperty(
        "drools.processInstanceManagerFactory",
        DefaultProcessInstanceManagerFactory.class.getName());
    SessionConfiguration conf = new SessionConfiguration(defaultProps);

    KieSession ksession = (StatefulKnowledgeSession) kbase.newKieSession(conf, env);
    return ksession;
  }
 private static KieSession createKieSession() {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(
       ResourceFactory.newClassPathResource("exceptions/ExceptionHandlingWithSignal.bpmn2"),
       ResourceType.BPMN2);
   KieBase kbase = kbuilder.newKnowledgeBase();
   return kbase.newKieSession();
 }
  protected void checkForValue(int value) {
    List<Integer> list = new ArrayList<Integer>();
    KieBase kieBase = (KieBase) container.getComponentInstance("KBase1");
    KieSession ksession = kieBase.newKieSession();

    ksession.setGlobal("list", list);
    ksession.fireAllRules();
    ksession.dispose();
    assertTrue("Expected:<" + value + "> but was:<" + list.get(0) + ">", list.get(0) == value);
  }
Example #8
0
 @Test
 public void testMVELUsingGlobalsInDebugMode() throws Exception {
   MVELDebugHandler.setDebugMode(true);
   try {
     KieBase kbase = loadKnowledgeBase("test_MVELGlobalDebug.drl");
     KieSession ksession = kbase.newKieSession();
     ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, false);
     ksession.dispose();
     MVELDebugHandler.setDebugMode(false);
   } catch (Exception e) {
     MVELDebugHandler.setDebugMode(false);
     e.printStackTrace();
     fail("Should not raise exceptions");
   }
 }
Example #9
0
  @Test
  public void testLocalVariableMVELConsequence() throws Exception {
    KieBase kbase = loadKnowledgeBase("test_LocalVariableMVELConsequence.drl");
    KieSession ksession = kbase.newKieSession();

    final List list = new ArrayList();
    ksession.setGlobal("results", list);

    ksession.insert(new Person("bob", "stilton"));
    ksession.insert(new Person("mark", "brie"));

    try {
      ksession.fireAllRules();

      assertEquals("should have fired twice", 2, list.size());

    } catch (Exception e) {
      e.printStackTrace();
      fail("Should not raise any exception");
    }
  }
Example #10
0
  @Test
  public void testHelloWorld() throws Exception {
    // read in the source
    KieBase kbase = loadKnowledgeBase("test_mvel.drl");
    KieSession ksession = kbase.newKieSession();

    final List list = new ArrayList();
    ksession.setGlobal("list", list);

    final List list2 = new ArrayList();
    ksession.setGlobal("list2", list2);

    Cheese c = new Cheese("stilton", 10);
    ksession.insert(c);
    ksession.fireAllRules();
    assertEquals(2, list.size());
    assertEquals(BigInteger.valueOf(30), list.get(0));
    assertEquals(Integer.valueOf(22), list.get(1));

    assertEquals("hello world", list2.get(0));

    Date dt = DateUtils.parseDate("10-Jul-1974");
    assertEquals(dt, c.getUsedBy());
  }
Example #11
0
  @Test
  public void testArrays() throws Exception {
    String text = "package test_mvel;\n";
    text += "import " + TestObject.class.getCanonicalName() + ";\n";
    text += "import function " + TestObject.class.getCanonicalName() + ".array;\n";
    text += "no-loop true\n";
    text += "dialect \"mvel\"\n";
    text += "rule \"1\"\n";
    text += "salience 1\n";
    text += "when\n";
    text += "    $fact: TestObject()\n";
    text += "    eval($fact.checkHighestPriority(\"mvel\", 2))\n";
    text +=
        "    eval($fact.stayHasDaysOfWeek(\"mvel\", false, new String[][]{{\"2008-04-01\", \"2008-04-10\"}}))\n";
    text += "then\n";
    text += "    $fact.applyValueAddPromo(1,2,3,4,\"mvel\");\n";
    text += "end";

    KieBase kieBase = loadKnowledgeBaseFromString(text.replaceAll("mvel", "java"), text);
    StatelessKieSession statelessKieSession = kieBase.newStatelessKieSession();

    List<String> list = new ArrayList<String>();
    statelessKieSession.execute(new TestObject(list));

    assertEquals(6, list.size());

    assertTrue(
        list.containsAll(
            Arrays.asList(
                "TestObject.checkHighestPriority: java|2",
                "TestObject.stayHasDaysOfWeek: java|false|[2008-04-01, 2008-04-10]",
                "TestObject.checkHighestPriority: mvel|2",
                "TestObject.stayHasDaysOfWeek: mvel|false|[2008-04-01, 2008-04-10]",
                "TestObject.applyValueAddPromo: 1|2|3|4|mvel",
                "TestObject.applyValueAddPromo: 1|2|3|4|java")));
  }
  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;
  }
 /**
  * 执行规则
  *
  * @param order
  * @param userRule
  */
 public void executeRule(Order order, final UserRule userRule) {
   System.out.println("Thread name =" + Thread.currentThread().getId());
   // initKBase();
   loadPackage(userRule);
   KieSession kieStatefulSession = (KieSession) kBase.newKieSession();
   //        KieSession kieStatefulSession = kBase.newStatefulKnowledgeSession();
   kieStatefulSession.insert(order);
   kieStatefulSession.insert(userRule);
   //        kieStatefulSession.startProcess(userRule.getUserCode());
   kieStatefulSession.fireAllRules(
       new AgendaFilter() {
         @Override
         public boolean accept(Match match) {
           return match.getRule().getPackageName().endsWith(userRule.getUserCode());
         }
       });
   kieStatefulSession.dispose();
   clearKiePackages();
 }
  /**
   * 加载规则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());
  }
 /** 清空kbase规则库 */
 private void clearKiePackages() {
   Iterator<KiePackage> it = kBase.getKiePackages().iterator();
   while (it.hasNext()) {
     kBase.removeKiePackage(it.next().getName());
   }
 }
Example #16
0
  private void createKnowledgeSessionStartProcessEtc(KieBase kbase) {
    logger.info("session count=" + kbase.getKieSessions().size());

    StatefulKnowledgeSession ksession =
        JPAKnowledgeService.newStatefulKnowledgeSession(
            kbase, getKnowledgeSessionConfiguration(), env);
    addEventListenersToSession(ksession);

    /**
     * The following log line caused the memory leak. The specific (reverse-ordered) stack trace is
     * the following:
     *
     * <p>MemoryLeakTest.createKnowledgeSessionStartProcessEtc(KnowledgeBase) calls
     * kbase.getKieSessions() .. KnowledgeBaseImpl.getStatefulKnowledgeSessions() line: 186
     * StatefulKnowledgeSessionImpl.<init>(ReteooWorkingMemory, KnowledgeBase) line: 121
     * ReteooStatefulSession(AbstractWorkingMemory).setKnowledgeRuntime(InternalKnowledgeRuntime)
     * line: 1268 ReteooStatefulSession(AbstractWorkingMemory).createProcessRuntime() line: 342
     * ProcessRuntimeFactory.newProcessRuntime(AbstractWorkingMemory) line: 12
     * ProcessRuntimeFactoryServiceImpl.newProcessRuntime(AbstractWorkingMemory) line: 1
     * ProcessRuntimeFactoryServiceImpl.newProcessRuntime(AbstractWorkingMemory) line: 10
     * ProcessRuntimeImpl.<init>(AbstractWorkingMemory) line: 84
     * ProcessRuntimeImpl.initProcessEventListeners() line: 215
     *
     * <p>And ProcessRuntimeImpl.initProcessEventListeners() is what adds a new listener to
     * AbstractRuleBase.eventSupport.listeners via this line (235):
     * kruntime.getKnowledgeBase().addEventListener(knowledgeBaseListener);
     *
     * <p>The StatefulKnowledgeSessionImpl instance created in this .getStatefulKnowledgeSessions()
     * method is obviously never disposed, which means that the listener is never removed. The
     * listener then contains a link to a field (signalManager) of the ProcessRuntimeImpl, which
     * contains a link to the StatefulKnowledgeSessionImpl instance created here. etc..
     */
    logger.info("session count=" + kbase.getKieSessions().size());

    TestWorkItemHandler handler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);

    try {
      // create process instance, insert into session and start process
      Map<String, Object> processParams = new HashMap<String, Object>();
      String[] fireballVarHolder = new String[1];
      processParams.put("fireball", fireballVarHolder);
      ProcessInstance processInstance = ksession.createProcessInstance(PROCESS_NAME, processParams);
      ksession.insert(processInstance);
      ksession.startProcessInstance(processInstance.getId());

      // after the log line has been added, the DefaultProcessEventListener registered
      //  in the addEventListenersToSession() method no longer works?!?
      ksession.fireAllRules();

      // test process variables
      String[] procVar =
          (String[]) ((WorkflowProcessInstance) processInstance).getVariable("fireball");
      assertEquals("Rule task did NOT fire or complete.", "boom!", procVar[0]);

      // complete task and process
      Map<String, Object> results = new HashMap<String, Object>();
      results.put("chaerg", new SerializableResult("zhrini", 302l, "F", "A", "T"));
      ksession.getWorkItemManager().completeWorkItem(handler.getWorkItem().getId(), results);

      assertNull(ksession.getProcessInstance(processInstance.getId()));
    } finally {
      // This should clean up all listeners, but doesn't -> see docs above
      ksession.dispose();
    }
  }
 public KieSession createSession() {
   return droolsKnowledgeBase.newKieSession();
 }
  @Override
  public void deploy(DeploymentUnit unit) {
    try {
      super.deploy(unit);
      if (!(unit instanceof KModuleDeploymentUnit)) {
        throw new IllegalArgumentException(
            "Invalid deployment unit provided - " + unit.getClass().getName());
      }
      KModuleDeploymentUnit kmoduleUnit = (KModuleDeploymentUnit) unit;
      DeployedUnitImpl deployedUnit = new DeployedUnitImpl(unit);

      // Create the release id
      KieContainer kieContainer = kmoduleUnit.getKieContainer();
      ReleaseId releaseId = null;
      if (kieContainer == null) {
        KieServices ks = KieServices.Factory.get();

        releaseId =
            ks.newReleaseId(
                kmoduleUnit.getGroupId(), kmoduleUnit.getArtifactId(), kmoduleUnit.getVersion());

        MavenRepository repository = getMavenRepository();
        repository.resolveArtifact(releaseId.toExternalForm());

        kieContainer = ks.newKieContainer(releaseId);

        kmoduleUnit.setKieContainer(kieContainer);
      }
      releaseId = kieContainer.getReleaseId();

      // retrieve the kbase name
      String kbaseName = kmoduleUnit.getKbaseName();
      if (StringUtils.isEmpty(kbaseName)) {
        KieBaseModel defaultKBaseModel =
            ((KieContainerImpl) kieContainer).getKieProject().getDefaultKieBaseModel();
        if (defaultKBaseModel != null) {
          kbaseName = defaultKBaseModel.getName();
        } else {
          kbaseName = DEFAULT_KBASE_NAME;
        }
      }
      InternalKieModule module =
          (InternalKieModule) ((KieContainerImpl) kieContainer).getKieModuleForKBase(kbaseName);
      if (module == null) {
        throw new IllegalStateException(
            "Cannot find kbase, either it does not exist or there are multiple default kbases in kmodule.xml");
      }

      KieBase kbase = kieContainer.getKieBase(kbaseName);
      Map<String, ProcessDescriptor> processDescriptors = new HashMap<String, ProcessDescriptor>();
      for (org.kie.api.definition.process.Process process : kbase.getProcesses()) {
        processDescriptors.put(
            process.getId(), (ProcessDescriptor) process.getMetaData().get("ProcessDescriptor"));
      }

      // TODO: add forms data?
      Collection<String> files = module.getFileNames();

      processResources(
          module, files, kieContainer, kmoduleUnit, deployedUnit, releaseId, processDescriptors);

      // process the files in the deployment
      if (module.getKieDependencies() != null) {
        Collection<InternalKieModule> dependencies = module.getKieDependencies().values();
        for (InternalKieModule depModule : dependencies) {

          logger.debug("Processing dependency module " + depModule.getReleaseId());
          files = depModule.getFileNames();

          processResources(
              depModule,
              files,
              kieContainer,
              kmoduleUnit,
              deployedUnit,
              depModule.getReleaseId(),
              processDescriptors);
        }
      }
      Collection<ReleaseId> dependencies =
          module.getJarDependencies(new DependencyFilter.ExcludeScopeFilter("test", "provided"));

      // process deployment dependencies
      if (dependencies != null && !dependencies.isEmpty()) {
        // Classes 2: classes added from project and dependencies added
        processClassloader(kieContainer, deployedUnit);
      }

      AuditEventBuilder auditLoggerBuilder =
          setupAuditLogger(identityProvider, unit.getIdentifier());

      RuntimeEnvironmentBuilder builder =
          boostrapRuntimeEnvironmentBuilder(
                  kmoduleUnit, deployedUnit, kieContainer, kmoduleUnit.getMergeMode())
              .knowledgeBase(kbase)
              .classLoader(kieContainer.getClassLoader());

      builder.registerableItemsFactory(
          getRegisterableItemsFactory(auditLoggerBuilder, kieContainer, kmoduleUnit));

      commonDeploy(unit, deployedUnit, builder.get(), kieContainer);
      kmoduleUnit.setDeployed(true);
    } catch (Throwable e) {
      logger.warn("Unexpected error while deploying unit {}", unit.getIdentifier(), e);
      // catch all possible errors to be able to report them to caller as RuntimeException
      throw new RuntimeException(e);
    }
  }