@Before
  public void setup() {
    TestUtil.cleanupSingletonSessionId();
    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION);
    List<String> processes = new ArrayList<String>();
    processes.add("BPMN2-ScriptTask.bpmn2");
    processes.add("BPMN2-UserTask.bpmn2");
    processes.add("BPMN2-CustomTask.bpmn2");

    InternalKieModule kJar1 = createKieJar(ks, releaseId, processes);
    File pom = new File("target/kmodule", "pom.xml");
    pom.getParentFile().mkdir();
    try {
      FileOutputStream fs = new FileOutputStream(pom);
      fs.write(getPom(releaseId).getBytes());
      fs.close();
    } catch (Exception e) {

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

    Properties properties = new Properties();
    properties.setProperty("mary", "HR");
    properties.setProperty("john", "HR");
    userGroupCallback = new JBossUserGroupCallbackImpl(properties);

    pds = TestUtil.setupPoolingDataSource();
  }
  @Test
  public void testUserTaskFromKjar() {
    KieServices ks = KieServices.Factory.get();

    RuntimeEnvironment environment =
        RuntimeEnvironmentBuilder.Factory.get()
            .newDefaultBuilder(ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION))
            .userGroupCallback(userGroupCallback)
            .get();

    manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    assertNotNull(manager);

    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    assertNotNull(engine);

    Map<String, Object> params = new HashMap<String, Object>();

    ProcessInstance processInstance = engine.getKieSession().startProcess("UserTask", params);

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

    long taskId = tasks.get(0).getId();

    engine.getTaskService().start(taskId, "john");
    engine.getTaskService().complete(taskId, "john", null);

    processInstance = engine.getKieSession().getProcessInstance(processInstance.getId());
    assertNull(processInstance);

    manager.disposeRuntimeEngine(engine);
  }
  @Test
  public void testScriptTaskFromKjarUsingNamedKbaseKsession() {
    KieServices ks = KieServices.Factory.get();

    RuntimeEnvironment environment =
        RuntimeEnvironmentBuilder.Factory.get()
            .newDefaultBuilder(
                ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION),
                "defaultKieBase",
                "defaultKieSession")
            .userGroupCallback(userGroupCallback)
            .get();

    manager = RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);
    assertNotNull(manager);

    RuntimeEngine engine = manager.getRuntimeEngine(EmptyContext.get());
    assertNotNull(engine);

    Map<String, Object> params = new HashMap<String, Object>();

    ProcessInstance processInstance = engine.getKieSession().startProcess("ScriptTask", params);

    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
  }
  @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.");
  }
  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.º 6
0
  @Test
  public void testMessageWithIncrementalBuild() throws Exception {
    // Some suitably duff DSL to generate errors
    String dsl1 = "bananna\n";

    // Some suitably valid DRL
    String drl1 =
        "import org.drools.compiler.Person;\n"
            + "rule R1\n"
            + "when\n"
            + "There is a Person\n"
            + "then\n"
            + "end\n";

    // Some suitably valid DRL
    String drl2 = "rule R2\n" + "when\n" + "then\n" + "end\n";

    KieServices ks = KieServices.Factory.get();

    KieFileSystem kfs =
        ks.newKieFileSystem()
            .write("src/main/resources/dsl.dsl", dsl1)
            .write("src/main/resources/drl.dslr", drl1);

    KieBuilder kieBuilder = ks.newKieBuilder(kfs).buildAll();
    Results fullBuildResults = kieBuilder.getResults();
    assertEquals(3, fullBuildResults.getMessages().size());

    kfs.write("src/main/resources/r2.drl", drl2);
    IncrementalResults incrementalBuildResults =
        ((InternalKieBuilder) kieBuilder).createFileSet("src/main/resources/r2.drl").build();

    assertEquals(0, incrementalBuildResults.getAddedMessages().size());
    assertEquals(0, incrementalBuildResults.getRemovedMessages().size());
  }
Exemplo n.º 7
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"));
  }
  private void testKieModuleMetaDataInMemory(boolean useTypeDeclaration) throws Exception {
    KieServices ks = KieServices.Factory.get();
    ReleaseId dependency = ks.newReleaseId("org.drools", "drools-core", "5.5.0.Final");
    ReleaseId releaseId = ks.newReleaseId("org.kie", "metadata-test", "1.0-SNAPSHOT");

    InternalKieModule kieModule =
        createKieJarWithClass(ks, releaseId, useTypeDeclaration, 2, 7, dependency);
    KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData(kieModule);
    checkDroolsCoreDep(kieModuleMetaData);

    Collection<String> testClasses = kieModuleMetaData.getClasses("org.kie.test");
    assertEquals(1, testClasses.size());
    assertEquals("Bean", testClasses.iterator().next());
    Class<?> beanClass = kieModuleMetaData.getClass("org.kie.test", "Bean");
    assertNotNull(beanClass.getMethod("getValue"));

    TypeMetaInfo beanTypeInfo = kieModuleMetaData.getTypeMetaInfo(beanClass);
    assertNotNull(beanTypeInfo);

    assertTrue(beanTypeInfo.isEvent());

    Role role = beanClass.getAnnotation(Role.class);
    assertNotNull(role);
    assertEquals(Role.Type.EVENT, role.value());

    assertEquals(useTypeDeclaration, beanTypeInfo.isDeclaredType());
  }
Exemplo n.º 9
0
  /**
   * Creating a KieBase from the workflow GAV specified in the config.
   *
   * @return KieBase for package SRAMPPackage
   * @throws SrampClientException
   * @throws SrampAtomException
   */
  public KieContainer getKieContainer(ReleaseId releaseId)
      throws SrampClientException, SrampAtomException {
    KieServices ks = KieServices.Factory.get();
    KieRepository repo = ks.getRepository();
    SrampAtomApiClient client = SrampAtomApiClientFactory.createAtomApiClient();

    Governance governance = new Governance();
    QueryResultSet results =
        client
            .buildQuery(SRAMP_KIE_JAR_QUERY)
            .parameter(governance.getGovernanceWorkflowGroup())
            .parameter(governance.getGovernanceWorkflowName())
            .parameter(governance.getGovernanceWorkflowVersion())
            .count(1)
            .query();
    if (results.size() > 0) {
      ArtifactSummary artifactSummery = results.get(0);
      InputStream is = client.getArtifactContent(artifactSummery);
      KieModule kModule = repo.addKieModule(ks.getResources().newInputStreamResource(is));
      logger.info(
          Messages.i18n.format(
              "KieSrampUtil.CreatingKieContainer", artifactSummery)); // $NON-NLS-1$
      KieContainer kContainer = ks.newKieContainer(kModule.getReleaseId());
      // Creating the KieBase for the SRAMPPackage
      logger.info(
          Messages.i18n.format(
              "KieSrampUtil.FindKieBase",
              governance.getGovernanceWorkflowPackage())); // $NON-NLS-1$
      return kContainer;
    } else {
      return null;
    }
  }
Exemplo n.º 10
0
  public List<ValidationMessage> validate(
      final Path resourcePath,
      final InputStream resource,
      final DirectoryStream.Filter<org.uberfire.java.nio.file.Path>... supportingFileFilters) {

    final Project project = projectService.resolveProject(resourcePath);
    if (project == null) {
      return Collections.emptyList();
    }

    final KieServices kieServices = KieServices.Factory.get();
    final KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
    final String projectPrefix = project.getRootPath().toURI();

    // Add Java Model files
    final org.uberfire.java.nio.file.Path nioProjectRoot = paths.convert(project.getRootPath());
    final DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream =
        Files.newDirectoryStream(nioProjectRoot);
    visitPaths(projectPrefix, kieFileSystem, directoryStream, supportingFileFilters);

    // Add resource to be validated
    final String destinationPath = resourcePath.toURI().substring(projectPrefix.length() + 1);
    final BufferedInputStream bis = new BufferedInputStream(resource);

    kieFileSystem.write(
        destinationPath, KieServices.Factory.get().getResources().newInputStreamResource(bis));

    // Validate
    final KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
    final Results kieResults = kieBuilder.buildAll().getResults();
    final List<ValidationMessage> results = convertMessages(kieResults);

    return results;
  }
Exemplo n.º 11
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.º 12
0
  @Test
  // See DROOLS-193 (KnowledgeBuilderResult does not always contain a Resource)
  public void testMessageFromInvalidDSL() throws Exception {
    // Some suitably duff DSL
    String dsl = "bananna\n";

    // Some suitably valid DRL
    String drl =
        "import org.drools.compiler.Person;\n"
            + "rule R1\n"
            + "when\n"
            + "There is a Person\n"
            + "then\n"
            + "end\n";

    KieServices ks = KieServices.Factory.get();

    KieFileSystem kfs =
        ks.newKieFileSystem()
            .write("src/main/resources/dsl.dsl", dsl)
            .write("src/main/resources/drl.dslr", drl);

    KieBuilder kieBuilder = ks.newKieBuilder(kfs).buildAll();
    Results results = kieBuilder.getResults();

    assertEquals(3, results.getMessages().size());
  }
  @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"));
  }
  protected static void deployKjar() {
    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION);
    List<String> processes = new ArrayList<String>();
    processes.add("processes/hiring.bpmn2");
    processes.add("processes/customtask.bpmn");
    processes.add("processes/humanTask.bpmn");
    processes.add("processes/signal.bpmn");
    processes.add("processes/import.bpmn");
    processes.add("processes/callactivity.bpmn");
    processes.add("processes/itemrefissue.bpmn");

    InternalKieModule kJar1 = createKieJar(ks, releaseId, processes);
    File pom = new File("target/kmodule", "pom.xml");
    pom.getParentFile().mkdir();
    try {
      FileOutputStream fs = new FileOutputStream(pom);
      fs.write(getPom(releaseId).getBytes());
      fs.close();
    } catch (Exception e) {

    }
    MavenRepository repository = getMavenRepository();
    repository.deployArtifact(releaseId, kJar1, pom);
  }
Exemplo n.º 15
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");
  }
Exemplo n.º 16
0
  @Test
  public void testGetRuleNames() {
    final KieServices ks = KieServices.Factory.get();

    final KieFileSystem kfs = ks.newKieFileSystem();
    kfs.write(
        "src/main/resources/test1.drl",
        "package org.test\n"
            + "rule A\n"
            + " when\n"
            + "then\n"
            + "end\n"
            + "rule B\n"
            + " when\n"
            + "then\n"
            + "end\n");
    kfs.write(
        "src/main/resources/test2.drl",
        "package org.test\n" + "rule C\n" + " when\n" + "then\n" + "end\n");

    final KieBuilder kieBuilder = ks.newKieBuilder(kfs);
    final List<Message> messages = kieBuilder.buildAll().getResults().getMessages();
    assertTrue(messages.isEmpty());

    final KieModule kieModule = kieBuilder.getKieModule();
    final KieModuleMetaData kieModuleMetaData =
        KieModuleMetaData.Factory.newKieModuleMetaData(kieModule);

    Collection<String> rules = kieModuleMetaData.getRuleNamesInPackage("org.test");
    assertEquals(3, rules.size());
    assertTrue(rules.containsAll(asList("A", "B", "C")));
  }
Exemplo n.º 17
0
  @Test
  public void testKieModuleMetaDataInMemoryWithJavaClassDefaultPackage() throws Exception {
    final KieServices ks = KieServices.Factory.get();
    final ReleaseId releaseId = ks.newReleaseId("org.kie", "javaDefaultPackage", "1.0-SNAPSHOT");
    final KieModuleModel kproj = ks.newKieModuleModel();

    final KieFileSystem kfs = ks.newKieFileSystem();
    kfs.writeKModuleXML(kproj.toXML())
        .writePomXML(generatePomXml(releaseId))
        .write("src/main/java/test/Bean.java", createJavaSource());

    final KieBuilder kieBuilder = ks.newKieBuilder(kfs);
    final List<Message> messages = kieBuilder.buildAll().getResults().getMessages();
    assertTrue(messages.isEmpty());

    final KieModule kieModule = kieBuilder.getKieModule();
    final KieModuleMetaData kieModuleMetaData =
        KieModuleMetaData.Factory.newKieModuleMetaData(kieModule);

    // The call to kieModuleMetaData.getClass() assumes a Java file has an explicit package
    final Class<?> beanClass = kieModuleMetaData.getClass("", "test.Bean");
    assertNotNull(beanClass);

    final TypeMetaInfo beanMetaInfo = kieModuleMetaData.getTypeMetaInfo(beanClass);
    assertNotNull(beanMetaInfo);
  }
Exemplo n.º 18
0
  private void testKieModuleMetaDataForDependenciesInMemory(boolean useTypeDeclaration)
      throws Exception {
    KieServices ks = KieServices.Factory.get();
    ReleaseId dependency = ks.newReleaseId("org.drools", "drools-core", "5.5.0.Final");
    ReleaseId releaseId = ks.newReleaseId("org.kie", "metadata-test", "1.0-SNAPSHOT");

    InternalKieModule kieModule =
        createKieJarWithClass(ks, releaseId, useTypeDeclaration, 2, 7, dependency);
    KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData(kieModule);
    checkDroolsCoreDep(kieModuleMetaData);

    Collection<String> testClasses = kieModuleMetaData.getClasses("org.drools");
    assertEquals(55, testClasses.size());
    Class<?> beanClass = kieModuleMetaData.getClass("org.drools", "QueryResult");
    assertNotNull(beanClass);

    // Classes in dependencies should have TypeMetaInfo
    TypeMetaInfo beanTypeInfo = kieModuleMetaData.getTypeMetaInfo(beanClass);
    assertNotNull(beanTypeInfo);

    if (useTypeDeclaration) {
      assertTrue(beanTypeInfo.isEvent());
    }

    assertEquals(useTypeDeclaration, beanTypeInfo.isDeclaredType());
  }
Exemplo n.º 19
0
  private static KieSession readKnowledgeBase() throws Exception {

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

    return kSession;
  }
Exemplo n.º 20
0
  @Test
  public void invokePmmlWithTrait() {

    String extraDrl =
        "package org.drools.pmml.pmml_4_2.test;"
            + ""
            + "import org.drools.core.factmodel.traits.Entity;"
            + ""
            + "rule \"Init\" "
            + "when "
            + "   $s : String( this == \"trigger\" ) "
            + "then "
            + "   System.out.println( \"Trig\" ); "
            + "   Entity o = new Entity(); "
            + "   insert( o ); \n"
            + ""
            +
            // don an object with the default input trait ( modelName + "Input" )
            // both soft and hard fields will be used to feed data into the model
            ""
            + "   MockColdTrait input = don( o, MockColdTrait.class ); "
            + "   modify( input ) { "
            + "       setTemp( 22.0 );"
            + "   } "
            + "end "
            + ""
            + ""
            + "rule Log when $x : MockColdTrait() then System.out.println( \"IN \" + $x ); end "
            + "rule Log2 when $x : Cold() then System.out.println( \"OUT \" + $x ); end ";

    KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem();

    kfs.write(ResourceFactory.newClassPathResource(pmmlSource).setResourceType(ResourceType.PMML));
    kfs.write(
        ResourceFactory.newByteArrayResource(extraDrl.getBytes())
            .setSourcePath("rules.drl")
            .setResourceType(ResourceType.DRL));

    Results res = ks.newKieBuilder(kfs).buildAll().getResults();
    if (res.hasMessages(Message.Level.ERROR)) {
      System.out.println(res.getMessages(Message.Level.ERROR));
    }
    assertEquals(0, res.getMessages(Message.Level.ERROR).size());

    KieSession kSession =
        ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();

    kSession.insert("trigger");
    kSession.fireAllRules();

    System.out.println(reportWMObjects(kSession));

    QueryResults qrs = kSession.getQueryResults("Cold", "MockCold", Variable.v);
    assertTrue(qrs.iterator().hasNext());
    Object val = qrs.iterator().next().get("$result");
    Assert.assertEquals(0.56, val);
  }
Exemplo n.º 21
0
 @Test
 public void testKieScannerOnClasspathContainerMustFail() {
   KieServices ks = KieServices.Factory.get();
   KieContainer kieContainer = ks.getKieClasspathContainer();
   try {
     KieScanner scanner = ks.newKieScanner(kieContainer);
     fail("Creating a KieScanner from a KieClasspathContainer must fail");
   } catch (RuntimeException e) {
   }
 }
  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.º 23
0
  @Before
  public void prepare() throws MalformedURLException {

    configureServices();
    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION);
    File kjar = new File("src/test/resources/kjar/custom-data-project-1.0.jar");
    File pom = new File("src/test/resources/kjar/pom.xml");
    MavenRepository repository = getMavenRepository();
    repository.deployArtifact(releaseId, kjar, pom);
  }
  private void addKieModuleToRepo(KieModuleModel kieProject) {
    KieBuilderImpl.setDefaultsforEmptyKieModule(kieProject);

    InternalKieModule kJar = createKieModule(kieProject);

    if (kJar != null) {
      KieServices ks = KieServices.Factory.get();
      log.info("adding KieModule from " + configFileURL.toExternalForm() + " to repository.");
      ks.getRepository().addKieModule(kJar);
      KieSpringUtils.setReleaseIdForContext(releaseId, context);
    }
  }
Exemplo n.º 25
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.º 26
0
  private void testKieModuleMetaDataInMemoryUsingPOM(boolean useTypeDeclaration) throws Exception {
    // Build a KieModule jar, deploy it into local Maven repository
    KieServices ks = KieServices.Factory.get();
    ReleaseId dependency = ks.newReleaseId("org.drools", "drools-core", "5.5.0.Final");
    ReleaseId releaseId = ks.newReleaseId("org.kie", "metadata-test", "1.0-SNAPSHOT");
    InternalKieModule kieModule =
        createKieJarWithClass(ks, releaseId, useTypeDeclaration, 2, 7, dependency);
    String pomText = getPom(dependency);
    File pomFile =
        new File(
            System.getProperty("java.io.tmpdir"),
            MavenRepository.toFileName(releaseId, null) + ".pom");
    try {
      FileOutputStream fos = new FileOutputStream(pomFile);
      fos.write(pomText.getBytes());
      fos.flush();
      fos.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    MavenRepository.getMavenRepository().deployArtifact(releaseId, kieModule, pomFile);

    // Build a second KieModule, depends on the first KieModule jar which we have deployed into
    // Maven
    ReleaseId releaseId2 = ks.newReleaseId("org.kie", "metadata-test-using-pom", "1.0-SNAPSHOT");
    String pomText2 = getPom(releaseId2, releaseId);
    File pomFile2 =
        new File(
            System.getProperty("java.io.tmpdir"),
            MavenRepository.toFileName(releaseId2, null) + ".pom");
    try {
      FileOutputStream fos = new FileOutputStream(pomFile2);
      fos.write(pomText2.getBytes());
      fos.flush();
      fos.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    KieModuleMetaData kieModuleMetaData = KieModuleMetaData.Factory.newKieModuleMetaData(pomFile2);
    // checkDroolsCoreDep(kieModuleMetaData);

    Collection<String> testClasses = kieModuleMetaData.getClasses("org.kie.test");
    assertEquals(1, testClasses.size());
    assertEquals("Bean", testClasses.iterator().next());
    Class<?> beanClass = kieModuleMetaData.getClass("org.kie.test", "Bean");
    assertNotNull(beanClass.getMethod("getValue"));

    if (useTypeDeclaration) {
      assertTrue(kieModuleMetaData.getTypeMetaInfo(beanClass).isEvent());
    }
  }
Exemplo n.º 27
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.º 28
0
  public static KieModule buildAndInstallKieModuleIntoRepo(
      final ReleaseId releaseId,
      final KieBaseTestConfiguration kieBaseConfiguration,
      final Resource... resources) {
    final KieServices kieServices = KieServices.Factory.get();

    final KieModuleModel module = kieServices.newKieModuleModel();
    final KieBaseModel base = kieBaseConfiguration.getKieBaseModel(module);
    final KieFileSystem fileSystem = getKieFileSystemWithKieModule(module, releaseId, resources);
    final KieBuilder builder = getKieBuilderFromKieFileSystem(fileSystem, true);
    final KieModule kieModule = builder.getKieModule();
    kieServices.getRepository().addKieModule(kieModule);
    return kieModule;
  }
Exemplo n.º 29
0
  public Builder(
      final Project project,
      final IOService ioService,
      final KieProjectService projectService,
      final ProjectImportsService importsService,
      final List<BuildValidationHelper> buildValidationHelpers,
      final PackageNameWhiteList packageNameWhiteList,
      final LRUProjectDependenciesClassLoaderCache dependenciesClassLoaderCache,
      final LRUPomModelCache pomModelCache) {
    this.project = project;
    this.ioService = ioService;
    this.projectService = projectService;
    this.importsService = importsService;
    this.buildValidationHelpers = buildValidationHelpers;
    this.packageNameWhiteList = packageNameWhiteList;
    this.projectGAV = project.getPom().getGav();
    this.projectRoot = Paths.convert(project.getRootPath());
    this.projectPrefix = projectRoot.toUri().toString();
    this.kieServices = KieServices.Factory.get();
    this.kieFileSystem = kieServices.newKieFileSystem();
    this.dependenciesClassLoaderCache = dependenciesClassLoaderCache;
    this.pomModelCache = pomModelCache;

    DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream =
        Files.newDirectoryStream(projectRoot);
    visitPaths(directoryStream);
  }
  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();
  }