/**
   * Test that illustrates that jobs are persisted and survives server restart and as soon as
   * GlobalTimerService is active jobs are fired NOTE: this test is disabled by default as it
   * requires real db (not in memory) and test to be executed separately each with new jvm process
   */
  @Test
  @Ignore
  public void testContinueGlobalTestService() throws Exception {
    SimpleRuntimeEnvironment environment = new DefaultRuntimeEnvironment();

    environment.addAsset(
        ResourceFactory.newClassPathResource("BPMN2-IntermediateCatchEventTimerCycle2.bpmn2"),
        ResourceType.BPMN2);
    environment.addToConfiguration(
        "drools.timerService", "org.jbpm.process.core.timer.impl.RegisteredTimerServiceDelegate");
    RuntimeManager manger =
        RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);

    // build GlobalTimerService instance

    TimerService globalTs = new GlobalTimerService(manger, globalScheduler);
    // and register it in the registry under 'default' key
    TimerServiceRegistry.getInstance().registerTimerService("default", globalTs);
    // prepare listener to assert results
    final List<Long> timerExporations = new ArrayList<Long>();
    ProcessEventListener listener =
        new DefaultProcessEventListener() {

          @Override
          public void afterNodeLeft(ProcessNodeLeftEvent event) {
            if (event.getNodeInstance().getNodeName().equals("timer")) {
              timerExporations.add(event.getProcessInstance().getId());
            }
          }
        };

    Thread.sleep(5000);
  }
  /**
   * Test that illustrates that jobs are persisted and survives server restart and as soon as
   * GlobalTimerService is active jobs are fired and it loads and aborts the process instance to
   * illustrate jobs are properly removed when isntance is aborted NOTE: this test is disabled by
   * default as it requires real db (not in memory) and test to be executed separately each with new
   * jvm process
   */
  @Test
  @Ignore
  public void testAbortGlobalTestService() throws Exception {
    SimpleRuntimeEnvironment environment = new DefaultRuntimeEnvironment();

    environment.addAsset(
        ResourceFactory.newClassPathResource("BPMN2-IntermediateCatchEventTimerCycle3.bpmn2"),
        ResourceType.BPMN2);
    environment.addToConfiguration(
        "drools.timerService", "org.jbpm.process.core.timer.impl.RegisteredTimerServiceDelegate");
    RuntimeManager manger =
        RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);

    // build GlobalTimerService instance

    TimerService globalTs = new GlobalTimerService(manger, globalScheduler);
    // and register it in the registry under 'default' key
    TimerServiceRegistry.getInstance().registerTimerService("default", globalTs);
    // prepare listener to assert results
    final List<Long> timerExporations = new ArrayList<Long>();
    ProcessEventListener listener =
        new DefaultProcessEventListener() {

          @Override
          public void afterNodeLeft(ProcessNodeLeftEvent event) {
            if (event.getNodeInstance().getNodeName().equals("timer")) {
              timerExporations.add(event.getProcessInstance().getId());
            }
          }
        };
    long id = -1;
    Thread.sleep(5000);
    Runtime runtime = manger.getRuntime(ProcessInstanceIdContext.get());
    KieSession ksession = runtime.getKieSession();
    ksession.addEventListener(listener);

    ksession.abortProcessInstance(id);
    ProcessInstance processInstance = ksession.getProcessInstance(id);
    assertNull(processInstance);
    // let's wait to ensure no more timers are expired and triggered
    Thread.sleep(3000);
    ksession.dispose();
  }
  public void commonDeploy(
      DeploymentUnit unit,
      DeployedUnitImpl deployedUnit,
      RuntimeEnvironment environemnt,
      KieContainer kieContainer) {

    synchronized (this) {
      if (deploymentsMap.containsKey(unit.getIdentifier())) {
        DeployedUnit deployed = deploymentsMap.remove(unit.getIdentifier());
        RuntimeManager manager = deployed.getRuntimeManager();
        manager.close();
      }
      RuntimeManager manager = null;
      deploymentsMap.put(unit.getIdentifier(), deployedUnit);
      ((SimpleRuntimeEnvironment) environemnt)
          .addToEnvironment("IdentityProvider", identityProvider);
      try {
        switch (unit.getStrategy()) {
          case SINGLETON:
            manager = managerFactory.newSingletonRuntimeManager(environemnt, unit.getIdentifier());
            break;
          case PER_REQUEST:
            manager = managerFactory.newPerRequestRuntimeManager(environemnt, unit.getIdentifier());
            break;

          case PER_PROCESS_INSTANCE:
            manager =
                managerFactory.newPerProcessInstanceRuntimeManager(
                    environemnt, unit.getIdentifier());
            break;
          default:
            throw new IllegalArgumentException("Invalid strategy " + unit.getStrategy());
        }
        ((InternalRuntimeManager) manager).setKieContainer(kieContainer);
        deployedUnit.setRuntimeManager(manager);
        DeploymentDescriptor descriptor =
            ((InternalRuntimeManager) manager).getDeploymentDescriptor();
        List<String> requiredRoles = descriptor.getRequiredRoles(DeploymentDescriptor.TYPE_EXECUTE);
        if (requiredRoles != null && !requiredRoles.isEmpty()) {
          ((InternalRuntimeManager) manager)
              .setSecurityManager(
                  new IdentityRolesSecurityManager(identityProvider, requiredRoles));
        }
        notifyOnDeploy(unit, deployedUnit);

      } catch (Throwable e) {
        deploymentsMap.remove(unit.getIdentifier());
        if (manager != null) {
          manager.close();
        }
        notifyOnUnDeploy(unit, deployedUnit);
        throw new RuntimeException(e);
      }
    }
  }