protected void initializeEntityCache() {

    final JobExecutorContext jobExecutorContext = Context.getJobExecutorContext();
    final ProcessEngineConfigurationImpl processEngineConfiguration =
        Context.getProcessEngineConfiguration();

    if (processEngineConfiguration != null
        && processEngineConfiguration.isDbEntityCacheReuseEnabled()
        && jobExecutorContext != null) {

      dbEntityCache = jobExecutorContext.getEntityCache();
      if (dbEntityCache == null) {
        dbEntityCache = new DbEntityCache(processEngineConfiguration.getDbEntityCacheKeyMapping());
        jobExecutorContext.setEntityCache(dbEntityCache);
      }

    } else {

      if (processEngineConfiguration != null) {
        dbEntityCache = new DbEntityCache(processEngineConfiguration.getDbEntityCacheKeyMapping());
      } else {
        dbEntityCache = new DbEntityCache();
      }
    }
  }
  public void afterPropertiesSet() throws Exception {

    dataSource =
        new PooledDataSource(
            ReflectUtil.getClassLoader(),
            "org.h2.Driver",
            "jdbc:h2:mem:DatabaseTablePrefixTest;DB_CLOSE_DELAY=1000;MVCC=TRUE;",
            "sa",
            "");

    // create schema in the
    Connection connection = dataSource.getConnection();
    connection.createStatement().execute("drop schema if exists SCHEMA1");
    connection.createStatement().execute("create schema SCHEMA1");
    connection.close();

    ProcessEngineConfigurationImpl config1 =
        createCustomProcessEngineConfiguration()
            .setProcessEngineName("DatabaseTablePrefixTest-engine1")
            .setDataSource(dataSource)
            .setDbMetricsReporterActivate(false)
            .setDatabaseSchemaUpdate("NO_CHECK"); // disable auto create/drop schema
    config1.setDatabaseTablePrefix("SCHEMA1.");
    ProcessEngine engine1 = config1.buildProcessEngine();

    // create the tables in SCHEMA1
    connection = dataSource.getConnection();
    connection.createStatement().execute("set schema SCHEMA1");
    engine1.getManagementService().databaseSchemaUpgrade(connection, "", "SCHEMA1");
    connection.close();

    engine1.close();
  }
  public static void waitForJobExecutorToProcessAllJobs(
      ProcessEngineConfigurationImpl processEngineConfiguration,
      long maxMillisToWait,
      long intervalMillis) {
    JobExecutor jobExecutor = processEngineConfiguration.getJobExecutor();
    jobExecutor.start();

    try {
      Timer timer = new Timer();
      InteruptTask task = new InteruptTask(Thread.currentThread());
      timer.schedule(task, maxMillisToWait);
      boolean areJobsAvailable = true;
      try {
        while (areJobsAvailable && !task.isTimeLimitExceeded()) {
          Thread.sleep(intervalMillis);
          areJobsAvailable = areJobsAvailable(processEngineConfiguration);
        }
      } catch (InterruptedException e) {
      } finally {
        timer.cancel();
      }
      if (areJobsAvailable) {
        throw new ProcessEngineException("time limit of " + maxMillisToWait + " was exceeded");
      }

    } finally {
      jobExecutor.shutdown();
    }
  }
  public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
    List<TypedValueSerializer> customSerializers = new ArrayList<TypedValueSerializer>();
    customSerializers.add(new ProcessInstanceVariableSerializer());
    customSerializers.add(new EnumVariableSerializer());

    processEngineConfiguration.setCustomPreVariableSerializers(customSerializers);
  }
  @Override
  public DmnDecisionTableResult execute(CommandContext commandContext) {
    ensureNotNull("decision definition id is null", "processDefinitionId", decisionDefinitionId);

    ProcessEngineConfigurationImpl processEngineConfiguration =
        commandContext.getProcessEngineConfiguration();
    DeploymentCache deploymentCache = processEngineConfiguration.getDeploymentCache();

    DecisionDefinitionEntity decisionDefinition =
        deploymentCache.findDeployedDecisionDefinitionById(decisionDefinitionId);

    // check authorization
    AuthorizationManager authorizationManager = commandContext.getAuthorizationManager();
    authorizationManager.checkEvaluateDecision(decisionDefinition.getKey());

    return doEvaluateDecision(decisionDefinition, variables);
  }
  public static ExecutionTree forExecution(final String executionId, ProcessEngine processEngine) {
    ProcessEngineConfigurationImpl configuration =
        (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration();

    CommandExecutor commandExecutor = configuration.getCommandExecutorTxRequired();

    ExecutionTree executionTree =
        commandExecutor.execute(
            new Command<ExecutionTree>() {
              public ExecutionTree execute(CommandContext commandContext) {
                ExecutionEntity execution =
                    commandContext.getExecutionManager().findExecutionById(executionId);
                return ExecutionTree.forExecution(execution);
              }
            });

    return executionTree;
  }
 public static boolean areJobsAvailable(
     ProcessEngineConfigurationImpl processEngineConfiguration) {
   return !processEngineConfiguration
       .getManagementService()
       .createJobQuery()
       .executable()
       .list()
       .isEmpty();
 }
 @Override
 protected void initJpa() {
   super.initJpa();
   if (jpaEntityManagerFactory != null) {
     sessionFactories.put(
         EntityManagerSession.class,
         new SpringEntityManagerSessionFactory(
             jpaEntityManagerFactory, jpaHandleTransaction, jpaCloseEntityManager));
   }
 }
 public static void dropSchema(ProcessEngineConfigurationImpl processEngineConfiguration) {
   processEngineConfiguration
       .getCommandExecutorTxRequired()
       .execute(
           new Command<Object>() {
             public Object execute(CommandContext commandContext) {
               commandContext.getDbSqlSession().dbSchemaDrop();
               return null;
             }
           });
 }
  public static void createSchema(ProcessEngineConfigurationImpl processEngineConfiguration) {
    processEngineConfiguration
        .getCommandExecutorTxRequired()
        .execute(
            new Command<Object>() {
              public Object execute(CommandContext commandContext) {

                commandContext.getSession(PersistenceSession.class).dbSchemaCreate();
                return null;
              }
            });
  }
 public static void deleteHistoryLevel(ProcessEngineConfigurationImpl processEngineConfiguration) {
   processEngineConfiguration
       .getCommandExecutorTxRequired()
       .execute(
           new Command<Object>() {
             public Object execute(CommandContext commandContext) {
               DbEntityManager dbEntityManager = commandContext.getDbEntityManager();
               PropertyEntity historyLevelProperty =
                   dbEntityManager.selectById(PropertyEntity.class, "historyLevel");
               if (historyLevelProperty != null) {
                 dbEntityManager.delete(historyLevelProperty);
               }
               return null;
             }
           });
 }
  /**
   * Required when user operations are logged that are not directly associated with a single
   * deployment (e.g. runtimeService.suspendProcessDefinitionByKey(..) with cascade to process
   * instances) and therefore cannot be cleaned up automatically during undeployment.
   */
  public static void clearOpLog(ProcessEngineConfigurationImpl processEngineConfiguration) {
    processEngineConfiguration
        .getCommandExecutorTxRequired()
        .execute(
            new Command<Void>() {

              public Void execute(CommandContext commandContext) {
                List<UserOperationLogEntry> logEntries =
                    commandContext
                        .getOperationLogManager()
                        .findOperationLogEntriesByQueryCriteria(
                            new UserOperationLogQueryImpl(), null);

                for (UserOperationLogEntry entry : logEntries) {
                  commandContext
                      .getOperationLogManager()
                      .deleteOperationLogEntryById(entry.getId());
                }

                return null;
              }
            });
  }
 public static void createOrUpdateHistoryLevel(
     final ProcessEngineConfigurationImpl processEngineConfiguration) {
   processEngineConfiguration
       .getCommandExecutorTxRequired()
       .execute(
           new Command<Object>() {
             public Object execute(CommandContext commandContext) {
               DbEntityManager dbEntityManager = commandContext.getDbEntityManager();
               PropertyEntity historyLevelProperty =
                   dbEntityManager.selectById(PropertyEntity.class, "historyLevel");
               if (historyLevelProperty != null) {
                 if (processEngineConfiguration.getHistoryLevel().getId()
                     != new Integer(historyLevelProperty.getValue())) {
                   historyLevelProperty.setValue(
                       Integer.toString(processEngineConfiguration.getHistoryLevel().getId()));
                   dbEntityManager.merge(historyLevelProperty);
                 }
               } else {
                 SchemaOperationsProcessEngineBuild.dbCreateHistoryLevel(dbEntityManager);
               }
               return null;
             }
           });
 }