@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);
  }
  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());
  }
  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());
  }
  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());
    }
  }
  @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");
  }
  @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());
  }
  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);
  }
  @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);
  }
  @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);
  }
  @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);
  }
  @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);
  }
  @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");
  }
  @Override
  public void undeploy(DeploymentUnit unit) {
    if (!(unit instanceof KModuleDeploymentUnit)) {
      throw new IllegalArgumentException(
          "Invalid deployment unit provided - " + unit.getClass().getName());
    }
    KModuleDeploymentUnit kmoduleUnit = (KModuleDeploymentUnit) unit;
    super.undeploy(unit);

    formManagerService.unRegisterForms(unit.getIdentifier());

    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId =
        ks.newReleaseId(
            kmoduleUnit.getGroupId(), kmoduleUnit.getArtifactId(), kmoduleUnit.getVersion());
    ks.getRepository().removeKieModule(releaseId);
  }
  @Before
  public void prepare() {
    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId(GROUP_ID, ARTIFACT_ID, VERSION);
    List<String> processes = new ArrayList<String>();
    processes.add("repo/processes/support/support.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);
  }
  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 testDeploymentOfProcessWithDescriptorKieConteinerInjection() {

    assertNotNull(deploymentService);

    KieServices ks = KieServices.Factory.get();
    ReleaseId releaseId = ks.newReleaseId(GROUP_ID, "kjar-with-dd", VERSION);
    List<String> processes = new ArrayList<String>();
    processes.add("repo/processes/general/customtask.bpmn");
    processes.add("repo/processes/general/humanTask.bpmn");
    processes.add("repo/processes/general/import.bpmn");

    DeploymentDescriptor customDescriptor = new DeploymentDescriptorImpl("org.jbpm.domain");
    customDescriptor
        .getBuilder()
        .runtimeStrategy(RuntimeStrategy.PER_REQUEST)
        .addWorkItemHandler(
            new NamedObjectModel(
                "mvel",
                "Log",
                "new org.jbpm.kie.services.test.objects.KieConteinerSystemOutWorkItemHandler(kieContainer)"));

    Map<String, String> resources = new HashMap<String, String>();
    resources.put(
        "src/main/resources/" + DeploymentDescriptor.META_INF_LOCATION, customDescriptor.toXml());

    InternalKieModule kJar1 = createKieJar(ks, releaseId, processes, resources);
    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);

    DeploymentUnit deploymentUnit =
        new KModuleDeploymentUnit(
            GROUP_ID, "kjar-with-dd", VERSION, "KBase-test", "ksession-test2");
    deploymentService.deploy(deploymentUnit);
    units.add(deploymentUnit);
    DeployedUnit deployedGeneral =
        deploymentService.getDeployedUnit(deploymentUnit.getIdentifier());
    assertNotNull(deployedGeneral);
    assertNotNull(deployedGeneral.getDeploymentUnit());
    assertNotNull(deployedGeneral.getRuntimeManager());

    DeploymentDescriptor descriptor =
        ((InternalRuntimeManager) deployedGeneral.getRuntimeManager()).getDeploymentDescriptor();
    assertNotNull(descriptor);
    assertEquals("org.jbpm.domain", descriptor.getPersistenceUnit());
    assertEquals("org.jbpm.domain", descriptor.getAuditPersistenceUnit());
    assertEquals(AuditMode.JPA, descriptor.getAuditMode());
    assertEquals(PersistenceMode.JPA, descriptor.getPersistenceMode());
    assertEquals(RuntimeStrategy.PER_REQUEST, descriptor.getRuntimeStrategy());
    assertEquals(0, descriptor.getMarshallingStrategies().size());
    assertEquals(0, descriptor.getConfiguration().size());
    assertEquals(0, descriptor.getEnvironmentEntries().size());
    assertEquals(0, descriptor.getEventListeners().size());
    assertEquals(0, descriptor.getGlobals().size());
    assertEquals(0, descriptor.getTaskEventListeners().size());
    assertEquals(1, descriptor.getWorkItemHandlers().size());
    assertEquals(0, descriptor.getRequiredRoles().size());

    RuntimeManager manager = deploymentService.getRuntimeManager(deploymentUnit.getIdentifier());
    assertNotNull(manager);

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

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

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

    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
    manager.disposeRuntimeEngine(engine);
  }
  @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);
    }
  }
Exemple #20
0
 public static ReleaseId generateReleaseId(final String groupId) {
   final KieServices kieServices = KieServices.Factory.get();
   return kieServices.newReleaseId(groupId, UUID.randomUUID().toString(), "1.0.0-SNAPSHOT");
 }
  @Override
  public void deploy(DeploymentUnit unit) {
    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);
    KieServices ks = KieServices.Factory.get();
    MavenRepository repository = getMavenRepository();
    repository.resolveArtifact(kmoduleUnit.getIdentifier());

    ReleaseId releaseId =
        ks.newReleaseId(
            kmoduleUnit.getGroupId(), kmoduleUnit.getArtifactId(), kmoduleUnit.getVersion());
    KieContainer kieContainer = ks.newKieContainer(releaseId);

    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 with name " + kbaseName);
    }

    Map<String, String> formsData = new HashMap<String, String>();
    Collection<String> files = module.getFileNames();
    for (String fileName : files) {
      if (fileName.matches(".+bpmn[2]?$")) {
        ProcessDesc process;
        try {
          String processString = new String(module.getBytes(fileName), "UTF-8");
          process = bpmn2Service.findProcessId(processString, kieContainer.getClassLoader());
          process.setEncodedProcessSource(Base64.encodeBase64String(processString.getBytes()));
          process.setDeploymentId(unit.getIdentifier());
          process.setForms(formsData);
          deployedUnit.addAssetLocation(process.getId(), process);
        } catch (UnsupportedEncodingException e) {
          logger.warn("Unable to load content for file '{}' : {}", fileName, e);
        }
      } else if (fileName.matches(".+ftl$")) {
        try {
          String formContent = new String(module.getBytes(fileName), "UTF-8");
          Pattern regex = Pattern.compile("(.{0}|.*/)([^/]*?)\\.ftl");
          Matcher m = regex.matcher(fileName);
          String key = fileName;
          while (m.find()) {
            key = m.group(2);
          }
          formsData.put(key, formContent);
        } catch (UnsupportedEncodingException e) {
          logger.warn("Unable to load content for form '{}' : {}", fileName, e);
        }
      } else if (fileName.matches(".+form$")) {
        try {
          String formContent = new String(module.getBytes(fileName), "UTF-8");
          Pattern regex = Pattern.compile("(.{0}|.*/)([^/]*?)\\.form");
          Matcher m = regex.matcher(fileName);
          String key = fileName;
          while (m.find()) {
            key = m.group(2);
          }
          formsData.put(key + ".form", formContent);
        } catch (UnsupportedEncodingException e) {
          logger.warn("Unable to load content for form '{}' : {}", fileName, e);
        }
      }
    }

    KieBase kbase = kieContainer.getKieBase(kbaseName);

    AbstractAuditLogger auditLogger = getAuditLogger();
    ServicesAwareAuditEventBuilder auditEventBuilder = new ServicesAwareAuditEventBuilder();
    auditEventBuilder.setIdentityProvider(identityProvider);
    auditEventBuilder.setDeploymentUnitId(unit.getIdentifier());
    auditLogger.setBuilder(auditEventBuilder);

    RuntimeEnvironmentBuilder builder =
        RuntimeEnvironmentBuilder.getDefault()
            .entityManagerFactory(getEmf())
            .knowledgeBase(kbase)
            .classLoader(kieContainer.getClassLoader());
    if (beanManager != null) {
      builder.registerableItemsFactory(
          InjectableRegisterableItemsFactory.getFactory(
              beanManager, auditLogger, kieContainer, kmoduleUnit.getKsessionName()));
    }
    commonDeploy(unit, deployedUnit, builder.get());
  }