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;
  }
Exemplo n.º 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"));
  }
Exemplo n.º 3
0
  @Test
  @Ignore
  public void testKScanner() throws Exception {
    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId("org.kie", "scanner-test", "1.0-SNAPSHOT");

    InternalKieModule kJar1 = createKieJar(ks, releaseId, "rule1", "rule2");
    KieContainer kieContainer = ks.newKieContainer(releaseId);

    MavenRepository repository = getMavenRepository();
    repository.deployArtifact(releaseId, kJar1, kPom);

    // create a ksesion and check it works as expected
    KieSession ksession = kieContainer.newKieSession("KSession1");
    checkKSession(ksession, "rule1", "rule2");

    // create a new kjar
    InternalKieModule kJar2 = createKieJar(ks, releaseId, "rule2", "rule3");

    // deploy it on maven
    repository.deployArtifact(releaseId, kJar2, kPom);

    // since I am not calling start() on the scanner it means it won't have automatic scheduled
    // scanning
    KieScanner scanner = ks.newKieScanner(kieContainer);

    // scan the maven repo to get the new kjar version and deploy it on the kcontainer
    scanner.scanNow();

    // create a ksesion and check it works as expected
    KieSession ksession2 = kieContainer.newKieSession("KSession1");
    checkKSession(ksession2, "rule2", "rule3");
  }
  @Test
  public void testGo() {
    KieServices ks = KieServices.Factory.get();
    KieContainer kContainer = ks.getKieClasspathContainer();

    KieSession ksession = kContainer.newKieSession();

    List<String> list = new ArrayList<String>();
    ksession.setGlobal("list", list);

    ksession.fireAllRules();

    assertEquals(2, list.size());
    assertTrue(list.contains("car"));
    assertTrue(list.contains("ball"));

    list.clear();

    ksession.insert("Debbie");
    ksession.fireAllRules();
    ksession.fireAllRules();

    assertEquals(1, list.size());
    assertTrue(list.contains("doll"));
  }
Exemplo n.º 5
0
  /**
   * This processes the deployment dependencies, which are made available by the {@link
   * KieContainer} {@link ClassLoader}.
   *
   * @param kieContainer The {@link KieContainer}, used to get the {@link ClassLoader}
   * @param deployedUnit The {@link DeployedUnitImpl}, used to store the classes loaded
   */
  protected void processClassloader(KieContainer kieContainer, DeployedUnitImpl deployedUnit) {
    if (kieContainer.getClassLoader() instanceof ProjectClassLoader) {
      ClassLoader parentCl = kieContainer.getClassLoader().getParent();
      if (parentCl instanceof URLClassLoader) {
        URL[] urls = ((URLClassLoader) parentCl).getURLs();
        if (urls == null || urls.length == 0) {
          return;
        }
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.addUrls(urls);
        builder.addClassLoader(kieContainer.getClassLoader());

        Reflections reflections = new Reflections(builder);

        Set<Class<?>> xmlRootElemClasses = reflections.getTypesAnnotatedWith(XmlRootElement.class);
        Set<Class<?>> xmlTypeClasses = reflections.getTypesAnnotatedWith(XmlType.class);
        Set<Class<?>> remoteableClasses = reflections.getTypesAnnotatedWith(Remotable.class);

        Set<Class<?>> allClasses = new HashSet<Class<?>>();
        for (Set<Class<?>> classesToAdd :
            new Set[] {xmlRootElemClasses, xmlTypeClasses, remoteableClasses}) {
          if (classesToAdd != null) {
            allClasses.addAll(classesToAdd);
          }
        }

        for (Class<?> clazz : allClasses) {
          filterClassesAddedToDeployedUnit(deployedUnit, clazz);
        }
      }
    }
  }
Exemplo n.º 6
0
  @Test
  @Ignore
  public void testScannerOnPomProject() throws Exception {
    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId1 = ks.newReleaseId("org.kie", "scanner-test", "1.0");
    ReleaseId releaseId2 = ks.newReleaseId("org.kie", "scanner-test", "2.0");

    MavenRepository repository = getMavenRepository();
    repository.deployPomArtifact("org.kie", "scanner-master-test", "1.0", createMasterKPom());

    resetFileManager();

    InternalKieModule kJar1 = createKieJarWithClass(ks, releaseId1, false, 2, 7);
    repository.deployArtifact(releaseId1, kJar1, createKPom(fileManager, releaseId1));

    KieContainer kieContainer =
        ks.newKieContainer(ks.newReleaseId("org.kie", "scanner-master-test", "LATEST"));
    KieSession ksession = kieContainer.newKieSession("KSession1");
    checkKSession(ksession, 14);

    KieScanner scanner = ks.newKieScanner(kieContainer);

    InternalKieModule kJar2 = createKieJarWithClass(ks, releaseId2, false, 3, 5);
    repository.deployArtifact(releaseId2, kJar2, createKPom(fileManager, releaseId1));

    scanner.scanNow();

    KieSession ksession2 = kieContainer.newKieSession("KSession1");
    checkKSession(ksession2, 15);
  }
Exemplo n.º 7
0
 @Test
 public void doTest() {
   logger.info("Testing simple process without persistence");
   KieContainer kc = KieServices.Factory.get().getKieClasspathContainer();
   KieSession ksession = kc.getKieBase("TestProcessKB").newKieSession();
   ksession.startProcess("HelloWorldProcess");
   ksession.dispose();
 }
Exemplo n.º 8
0
 public static KieBase getKieBaseFromReleaseIdByName(final ReleaseId id, final String name) {
   final KieContainer container = KieServices.Factory.get().newKieContainer(id);
   if (name == null) {
     return container.getKieBase();
   } else {
     return container.getKieBase(name);
   }
 }
Exemplo n.º 9
0
  private static KieSession readKnowledgeBase() throws Exception {

    KieServices ks = KieServices.Factory.get();
    KieContainer kContainer = ks.getKieClasspathContainer();
    KieSession kSession = kContainer.newKieSession();

    return kSession;
  }
  public static void main(String[] args) {

    LOGGER.debug("Initializing KieServices and KieContainer.");
    KieServices kieServices = KieServices.Factory.get();
    KieContainer kieContainer = kieServices.newKieClasspathContainer();
    KieSession kieSession = kieContainer.newKieSession();

    testExpiration(kieSession);

    kieSession.dispose();
  }
Exemplo n.º 11
0
  @Test
  @Ignore
  public void testLoadKieJarFromMavenRepo() throws Exception {
    // This test depends from the former one (UGLY!) and must be run immediately after it
    KieServices ks = KieServices.Factory.get();

    KieContainer kieContainer =
        ks.newKieContainer(ks.newReleaseId("org.kie", "scanner-test", "1.0-SNAPSHOT"));

    KieSession ksession2 = kieContainer.newKieSession("KSession1");
    checkKSession(ksession2, 15);
  }
Exemplo n.º 12
0
  @Test
  public void testLocalTaskService() throws Exception {

    // Create the task service
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.jbpm.services.task");
    DefaultUserGroupCallbackImpl userGroupCallback = new DefaultUserGroupCallbackImpl();
    // create mock groups
    userGroupCallback.addUser("john", "users");
    userGroupCallback.addUser("Administrator", "users");
    // start taskService
    TaskService taskService =
        HumanTaskServiceFactory.newTaskServiceConfigurator()
            .entityManagerFactory(emf)
            .userGroupCallback(userGroupCallback)
            .getTaskService();

    // Create the KIE session
    KieServices ks = KieServices.Factory.get();
    KieContainer kc = ks.getKieClasspathContainer();
    KieSession ksession = kc.newKieSession();

    // create the work item handler for human task
    WorkItemHandler humanTaskHandler = new NonManagedLocalHTWorkItemHandler(ksession, taskService);
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", humanTaskHandler);

    WorkflowProcessInstance instance =
        (WorkflowProcessInstance) ksession.startProcess("htHomeworkProcess", null);
    Assert.assertEquals(ProcessInstance.STATE_ACTIVE, instance.getState());

    List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner("john", "en-UK");
    Assert.assertNotNull(tasks);
    Assert.assertEquals(1, tasks.size());

    TaskSummary firstTask = tasks.iterator().next();

    Assert.assertNotNull(instance.getVariable("requestId"));
    String requestId = instance.getVariable("requestId").toString();

    InternalTask actualFirstTask = (InternalTask) taskService.getTaskById(firstTask.getId());
    System.out.println("requestId = " + requestId);
    System.out.println("formName = " + actualFirstTask.getFormName());
    Assert.assertNotNull(actualFirstTask.getFormName());
    Assert.assertTrue(actualFirstTask.getFormName().contains(requestId));

    taskService.claim(firstTask.getId(), "john");
    taskService.start(firstTask.getId(), "john");
    taskService.complete(firstTask.getId(), "john", null);

    // now that the second task is completed, the process is completed as well
    Assert.assertEquals(ProcessInstance.STATE_COMPLETED, instance.getState());
  }
Exemplo n.º 13
0
  public void init(boolean exitOnClose) {
    KieContainer kc = KieServices.Factory.get().getKieClasspathContainer();
    System.out.println(kc.verify().getMessages().toString());
    final KieSession serverKsession = kc.newKieSession("WumpusMainKS");
    final KieSession clientKsession = kc.newKieSession("WumpusClientKS");

    serverKsession
        .getChannels()
        .put(
            "sensors",
            new Channel() {
              public void send(Object object) {
                clientKsession.insert(object);
                //                clientKsession.fireAllRules();
              }
            });

    clientKsession
        .getChannels()
        .put(
            "commands",
            new Channel() {
              public void send(Object object) {
                serverKsession.insert(object);
                //                serverKsession.fireAllRules();
              }
            });

    WumpusWorldConfiguration wumpusWorldConfiguration = new WumpusWorldConfiguration();
    wumpusWorldConfiguration.setExitOnClose(exitOnClose);
    serverKsession.setGlobal("wumpusWorldConfiguration", wumpusWorldConfiguration);
    serverKsession.setGlobal("randomInteger", new java.util.Random());

    new Thread(
            new Runnable() {
              public void run() {
                serverKsession.fireUntilHalt();
              }
            })
        .start();

    new Thread(
            new Runnable() {
              public void run() {
                clientKsession.fireUntilHalt();
              }
            })
        .start();
    //        serverKsession.fireAllRules();
    //        clientKsession.fireAllRules();
  }
  public static void main(final String[] args) {
    KieContainer kc = KieServices.Factory.get().getKieClasspathContainer();
    KieSession ksession = kc.newKieSession("FibonacciKS");

    // KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession,
    // "log/fibonacci.log");

    ksession.insert(
        new Fibonacci(50)); // This is all that's need to start the recursion calculating the #'s.
    ksession.fireAllRules();

    // logger.close();
    ksession.dispose(); // Stateful rule session must always be disposed when finished
  }
Exemplo n.º 15
0
  public synchronized void setKieContainer(KieContainer kieContainer) {
    if (this.kieContainer != null) {
      throw new RuntimeException("Cannot change KieContainer on an already initialized KieScanner");
    }
    this.kieContainer = (InternalKieContainer) kieContainer;
    ReleaseId containerReleaseId = this.kieContainer.getContainerReleaseId();
    if (containerReleaseId == null) {
      throw new RuntimeException(
          "The KieContainer's ReleaseId cannot be null. Are you using a KieClasspathContainer?");
    }

    artifactResolver = getResolverFor(kieContainer.getReleaseId(), true);

    if (!isFixedVersion(containerReleaseId.getVersion())) {
      usedDependencies.put(
          containerReleaseId,
          new DependencyDescriptor(
              this.kieContainer.getReleaseId(), this.kieContainer.getCreationTimestamp()));
    }

    indexAtifacts();
    KieScannersRegistry.register(this);
    status = Status.STOPPED;

    if (MBeanUtils.isMBeanEnabled()) {
      mbean = new KieScannerMBeanImpl(this);
    }
  }
  public void go(PrintStream out) {
    KieServices ks = KieServices.Factory.get();
    KieRepository kr = ks.getRepository();

    KieModule kModule =
        kr.addKieModule(ks.getResources().newFileSystemResource(getFile("named-kiesession")));

    KieContainer kContainer = ks.newKieContainer(kModule.getReleaseId());

    KieSession kSession = kContainer.newKieSession("ksession1");
    kSession.setGlobal("out", out);

    Object msg1 = createMessage(kContainer, "Dave", "Hello, HAL. Do you read me, HAL?");
    kSession.insert(msg1);
    kSession.fireAllRules();
  }
Exemplo n.º 17
0
  /**
   * Goes through all files in a deployment, and processes them so that they are then ready for use
   * after deployment.
   *
   * @param module The {@link InternalKieModule}, necessary to get form content
   * @param files The {@link List} of file (names) to process.
   * @param kieContainer The {@link KieContainer}, necesary in order to load classes
   * @param deploymentUnit The {@link DeploymentUnit}, necessary to get the deployment id
   * @param deployedUnit The {@link DeployedUnit}, which contains the results of actions here
   */
  protected void processResources(
      InternalKieModule module,
      Collection<String> files,
      KieContainer kieContainer,
      DeploymentUnit unit,
      DeployedUnitImpl deployedUnit,
      ReleaseId releaseId,
      Map<String, ProcessDescriptor> processes) {
    for (String fileName : files) {
      if (fileName.matches(".+bpmn[2]?$")) {
        ProcessAssetDesc process;
        try {
          String processString = new String(module.getBytes(fileName), "UTF-8");
          String processId = getProcessId(processString);
          ProcessDescriptor processDesriptor = processes.get(processId);
          if (processDesriptor != null) {
            process = processDesriptor.getProcess();
            if (process == null) {
              throw new IllegalArgumentException("Unable to read process " + fileName);
            }
            process.setEncodedProcessSource(Base64.encodeBase64String(processString.getBytes()));
            process.setDeploymentId(unit.getIdentifier());

            deployedUnit.addAssetLocation(process.getId(), process);
            bpmn2Service.addProcessDefinition(
                unit.getIdentifier(), processId, processDesriptor, kieContainer);
          }
        } catch (UnsupportedEncodingException e) {
          throw new IllegalArgumentException(
              "Unsupported encoding while processing process " + fileName);
        }
      } else if (fileName.matches(".+ftl$")
          || fileName.matches(".+form$")
          || fileName.matches(".+frm$")) {
        try {
          String formContent = new String(module.getBytes(fileName), "UTF-8");
          if (fileName.indexOf("/") != -1)
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
          formManagerService.registerForm(unit.getIdentifier(), fileName, formContent);
        } catch (UnsupportedEncodingException e) {
          throw new IllegalArgumentException(
              "Unsupported encoding while processing form " + fileName);
        }
      } else if (fileName.matches(".+class$")) {
        // Classes 1: classes from deployment added
        String className = fileName.replaceAll("/", ".");
        className = className.substring(0, fileName.length() - ".class".length());
        Class deploymentClass = null;
        try {
          deploymentClass = kieContainer.getClassLoader().loadClass(className);
        } catch (ClassNotFoundException cnfe) {
          throw new IllegalArgumentException("Class " + className + " not found in the project");
        } catch (NoClassDefFoundError e) {
          throw new IllegalArgumentException("Class " + className + " not found in the project");
        }
        addClassToDeployedUnit(deploymentClass, deployedUnit);
      }
    }
  }
Exemplo n.º 18
0
  @Test
  @Ignore
  public void testTypeAndRuleInDifferentKieModules() throws Exception {
    KieServices ks = KieServices.Factory.get();

    ReleaseId depId = ks.newReleaseId("org.kie", "test-types", "1.0");
    InternalKieModule kJar1 = createKieJarWithType(ks, depId);
    MavenRepository repository = getMavenRepository();
    repository.deployArtifact(depId, kJar1, kPom);

    ReleaseId releaseId = ks.newReleaseId("org.kie", "test-rules", "1.0");
    InternalKieModule kieModule = createKieJarWithRules(ks, releaseId, depId);

    KieContainer kieContainer = ks.newKieContainer(releaseId);
    KieSession ksession = kieContainer.newKieSession("KSession1");
    checkKSession(ksession, 15);
  }
  private void checkValue(KieContainer kieContainer, int value) {
    List<Integer> list = new ArrayList<Integer>();
    KieSession ksession = kieContainer.newKieSession("KSession1");

    ksession.setGlobal("list", list);
    ksession.fireAllRules();
    ksession.dispose();
    assertTrue("Expected:<" + value + "> but was:<" + list.get(0) + ">", list.get(0) == value);
  }
Exemplo n.º 20
0
  public static void main(String[] args) {
    Begeta begeta = new Begeta();
    begeta.setName("kingson");
    begeta.setLevel("top");

    KieSession ksession = kc.newKieSession("begeta_session");
    ksession.insert(begeta);
    ksession.fireAllRules();
    ksession.dispose();
  }
Exemplo n.º 21
0
  /**
   * This method loads the rule base associated with the Drools event processor.
   *
   * @return The knowledge base
   */
  private KieBase loadRuleBase() {
    String droolsRuleBase = getRuleName() + ".drl";

    try {
      KieServices ks = KieServices.Factory.get();
      KieRepository kr = ks.getRepository();

      KieModuleModel kmm = ks.newKieModuleModel();
      KieBaseModel kbm =
          kmm.newKieBaseModel(getRuleName())
              .setEqualsBehavior(EqualityBehaviorOption.EQUALITY)
              .setEventProcessingMode(EventProcessingOption.STREAM);
      kbm.setDefault(true);

      KieFileSystem kfs = ks.newKieFileSystem();
      kfs.write(
          "src/main/resources/" + kbm.getName() + "/rule1.drl",
          ks.getResources().newClassPathResource(droolsRuleBase));
      kfs.writeKModuleXML(kmm.toXML());

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

      KieContainer container = ks.newKieContainer(kr.getDefaultReleaseId());
      KieBase kbase = container.getKieBase();
      // TODO: hack it for now, this attribute should be supported in the following drools6 release.
      System.setProperty("kie.mbean", "enabled");
      return kbase;

    } catch (Throwable e) {
      LOG.log(
          Level.SEVERE,
          MessageFormat.format(
              java.util.PropertyResourceBundle.getBundle("ep-drools.Messages")
                  .getString("EP-DROOLS-1"),
              droolsRuleBase,
              getRuleName()),
          e);
    }

    return (null);
  }
Exemplo n.º 22
0
  protected Object getInstanceFromModel(
      ObjectModel model, KieContainer kieContainer, Map<String, Object> contaxtParams) {
    ObjectModelResolver resolver = ObjectModelResolverProvider.get(model.getResolver());
    if (resolver == null) {
      // if we don't throw an exception here, we have an NPE below..
      throw new IllegalStateException(
          "Unable to find ObjectModelResolver for " + model.getResolver());
    }

    return resolver.getInstance(model, kieContainer.getClassLoader(), contaxtParams);
  }
  @Test
  public void testKJar() throws Exception {
    KieServices ks = KieServices.Factory.get();
    KieContainer kContainer = ks.getKieClasspathContainer();
    KieSession kSession = kContainer.newKieSession("FireAlarmKBase.session");

    Room room = new Room("101");
    kSession.insert(room);
    Sprinkler sprinkler = new Sprinkler(room);
    kSession.insert(sprinkler);
    Fire fire = new Fire(room);
    FactHandle fireFH = kSession.insert(fire);

    int rules = kSession.fireAllRules();
    assertEquals(2, rules);

    kSession.delete(fireFH);
    rules = kSession.fireAllRules();
    assertEquals(3, rules);
  }
 private static Object createMessage(KieContainer kContainer, String name, String text) {
   Object o = null;
   try {
     Class cl =
         kContainer.getClassLoader().loadClass("org.drools.example.api.namedkiesession.Message");
     o = cl.getConstructor(new Class[] {String.class, String.class}).newInstance(name, text);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return o;
 }
Exemplo n.º 25
0
  @Test
  @Ignore
  public void testKScannerWithRange() throws Exception {
    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId1 = ks.newReleaseId("org.kie", "scanner-test", "1.0.1");
    ReleaseId releaseId2 = ks.newReleaseId("org.kie", "scanner-test", "1.0.2");
    ReleaseId releaseRange = ks.newReleaseId("org.kie", "scanner-test", "[1.0.0,)");

    InternalKieModule kJar1 = createKieJar(ks, releaseId1, "rule1", "rule2");
    KieContainer kieContainer = ks.newKieContainer(releaseRange);

    MavenRepository repository = getMavenRepository();
    repository.deployArtifact(releaseId1, kJar1, kPom);

    // create a ksesion and check it works as expected
    KieSession ksession = kieContainer.newKieSession("KSession1");
    checkKSession(ksession, "rule1", "rule2");

    // create a new kjar
    InternalKieModule kJar2 = createKieJar(ks, releaseId2, "rule2", "rule3");

    // deploy it on maven
    repository.deployArtifact(releaseId2, kJar2, kPom);

    // since I am not calling start() on the scanner it means it won't have automatic scheduled
    // scanning
    InternalKieScanner scanner = (InternalKieScanner) ks.newKieScanner(kieContainer);
    assertEquals(releaseId1, scanner.getCurrentReleaseId());
    assertEquals(InternalKieScanner.Status.STOPPED, scanner.getStatus());

    // scan the maven repo to get the new kjar version and deploy it on the kcontainer
    scanner.scanNow();
    assertEquals(releaseId2, scanner.getCurrentReleaseId());
    assertEquals(InternalKieScanner.Status.STOPPED, scanner.getStatus());

    // create a ksesion and check it works as expected
    KieSession ksession2 = kieContainer.newKieSession("KSession1");
    checkKSession(ksession2, "rule2", "rule3");
  }
Exemplo n.º 26
0
  private void testKScannerWithType(boolean useTypeDeclaration) throws Exception {
    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId("org.kie", "scanner-test", "1.0-SNAPSHOT");

    InternalKieModule kJar1 = createKieJarWithClass(ks, releaseId, useTypeDeclaration, 2, 7);

    MavenRepository repository = getMavenRepository();
    repository.deployArtifact(releaseId, kJar1, kPom);

    KieContainer kieContainer = ks.newKieContainer(releaseId);
    KieScanner scanner = ks.newKieScanner(kieContainer);

    KieSession ksession = kieContainer.newKieSession("KSession1");
    checkKSession(ksession, 14);

    InternalKieModule kJar2 = createKieJarWithClass(ks, releaseId, useTypeDeclaration, 3, 5);
    repository.deployArtifact(releaseId, kJar2, kPom);

    scanner.scanNow();

    KieSession ksession2 = kieContainer.newKieSession("KSession1");
    checkKSession(ksession2, 15);
  }
  @Test
  public void testImplicit() {
    KieServices ks = KieServices.Factory.get();
    KieContainer kContainer = ks.getKieClasspathContainer();
    KieSession ksession = kContainer.newKieSession("ksession-samples");
    ProcessInstance processInstance = ksession.startProcess("approveorder");

    Purchase purchase = new Purchase();
    purchase.setCustomerName("sekhar");
    purchase.setPaymentMethod(PaymentMethod.DEBIT);
    purchase.setSubtotal(0);
    ksession.insert(purchase);
    int rulesFired = ksession.fireAllRules();
    System.out.println("facthandles count -->" + ksession.getFactHandles().size());
    // Check the count
    Assert.assertEquals(1, rulesFired);
    // Check the node exists
    // assertNodeExists(processInstance, "Discount","printout");
    // Check the node names
    // assertNodeTriggered(processInstance.getId(),"Discount","printout");
    // Assert completed
    assertProcessInstanceCompleted(processInstance.getId(), ksession);
  }
  @RequestMapping(
      value = {"/ageRule"},
      consumes = {"application/json"},
      produces = {"application/json"},
      method = {RequestMethod.POST, RequestMethod.PUT})
  @ResponseBody
  public Person ageRuleConsumeAlcohol(@RequestBody Person person) {
    /*{"name":"Ashvin Domadia","age":21,"dob":1441058639091}*/

    KieSession kSession = kContainer.newKieSession("kSessionful");
    kSession.insert(person);
    kSession.fireAllRules();
    return person;
  }
  public static void execute(KieContainer kc) {
    KieSession ksession = kc.newKieSession("TroubleTicketWithDTKS");

    final Customer a = new Customer("A", "Drools", "Gold");
    final Customer b = new Customer("B", "Drools", "Platinum");
    final Customer c = new Customer("C", "Drools", "Silver");
    final Customer d = new Customer("D", "Drools", "Silver");

    final Ticket t1 = new Ticket(a);
    final Ticket t2 = new Ticket(b);
    final Ticket t3 = new Ticket(c);
    final Ticket t4 = new Ticket(d);

    ksession.insert(a);
    ksession.insert(b);
    ksession.insert(c);
    ksession.insert(d);

    ksession.insert(t1);
    ksession.insert(t2);
    final FactHandle ft3 = ksession.insert(t3);
    ksession.insert(t4);

    ksession.fireAllRules();

    t3.setStatus("Done");

    ksession.update(ft3, t3);

    try {
      System.err.println("[[ Sleeping 5 seconds ]]");
      Thread.sleep(5000);
    } catch (final InterruptedException e) {
      e.printStackTrace();
    }

    System.err.println("[[ awake ]]");

    ksession.fireAllRules();

    ksession.dispose();
  }
 @Override
 protected void addExtraCustomClasses(Map<String, Class<?>> extraClasses) throws Exception {
   KieContainer kieContainer = KieServices.Factory.get().newKieContainer(kjar1);
   extraClasses.put(
       PERSON_CLASS_NAME, Class.forName(PERSON_CLASS_NAME, true, kieContainer.getClassLoader()));
 }