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 ByteArrayEntity getByteArrayValue() {
   if ((byteArrayValue == null) && (byteArrayId != null)) {
     // no lazy fetching outside of command context
     if (Context.getCommandContext() != null) {
       byteArrayValue =
           Context.getCommandContext()
               .getDbEntityManager()
               .selectById(ByteArrayEntity.class, byteArrayId);
     }
   }
   return byteArrayValue;
 }
  @Override
  public List<ProcessDefinition> executeList(CommandContext commandContext, Page page) {
    checkQueryOk();
    List<ProcessDefinition> list =
        commandContext
            .getProcessDefinitionManager()
            .findProcessDefinitionsByQueryCriteria(this, page);

    for (ProcessDefinition processDefinition : list) {

      BpmnModelInstance bpmnModelInstance =
          Context.getProcessEngineConfiguration()
              .getDeploymentCache()
              .findBpmnModelInstanceForProcessDefinition(
                  (ProcessDefinitionEntity) processDefinition);

      ModelElementInstance processElement =
          bpmnModelInstance.getModelElementById(processDefinition.getKey());
      if (processElement != null) {
        Collection<Documentation> documentations =
            processElement.getChildElementsByType(Documentation.class);
        List<String> docStrings = new ArrayList<String>();
        for (Documentation documentation : documentations) {
          docStrings.add(documentation.getTextContent());
        }

        ProcessDefinitionEntity processDefinitionEntity =
            (ProcessDefinitionEntity) processDefinition;
        processDefinitionEntity.setProperty(
            BpmnParse.PROPERTYNAME_DOCUMENTATION, BpmnParse.parseDocumentation(docStrings));
      }
    }

    return list;
  }
  public void deleteHistoricProcessInstanceById(String historicProcessInstanceId) {
    if (historyLevel > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE) {
      CommandContext commandContext = Context.getCommandContext();
      HistoricProcessInstanceEntity historicProcessInstance =
          findHistoricProcessInstance(historicProcessInstanceId);

      commandContext
          .getHistoricDetailManager()
          .deleteHistoricDetailsByProcessInstanceId(historicProcessInstanceId);

      commandContext
          .getHistoricVariableInstanceManager()
          .deleteHistoricVariableInstanceByProcessInstanceId(historicProcessInstanceId);

      commandContext
          .getHistoricActivityInstanceManager()
          .deleteHistoricActivityInstancesByProcessInstanceId(historicProcessInstanceId);

      commandContext
          .getHistoricTaskInstanceManager()
          .deleteHistoricTaskInstancesByProcessInstanceId(historicProcessInstanceId);

      getDbSqlSession().delete(historicProcessInstance);
    }
  }
  public Void execute(CommandContext commandContext) {
    if (messageName == null) {
      throw new ProcessEngineException("messageName cannot be null");
    }

    CorrelationHandler correlationHandler =
        Context.getProcessEngineConfiguration().getCorrelationHandler();

    CorrelationSet correlationSet = new CorrelationSet(businessKey, correlationKeys);
    Execution matchingExecution =
        correlationHandler.correlateMessageToExecution(commandContext, messageName, correlationSet);
    ProcessDefinition matchingDefinition =
        correlationHandler.correlateMessageToProcessDefinition(commandContext, messageName);

    if (matchingExecution != null && matchingDefinition != null) {
      throw new ProcessEngineException(
          "An execution and a process definition match the correlation.");
    }

    if (matchingExecution != null) {
      triggerExecution(commandContext, matchingExecution);
      return null;
    }

    if (matchingDefinition != null) {
      instantiateProcess(commandContext, matchingDefinition);
      return null;
    }

    throw new ProcessEngineException("Could not correlate message " + messageName);
  }
  protected MessageCorrelationResult tryCorrelateMessageToProcessDefinition(
      CommandContext commandContext, String messageName, CorrelationSet correlationSet) {

    MessageEventSubscriptionEntity messageEventSubscription =
        commandContext
            .getEventSubscriptionManager()
            .findMessageStartEventSubscriptionByName(messageName);
    if (messageEventSubscription == null || messageEventSubscription.getConfiguration() == null) {
      return null;

    } else {
      DeploymentCache deploymentCache =
          Context.getProcessEngineConfiguration().getDeploymentCache();

      String processDefinitionId = messageEventSubscription.getConfiguration();
      ProcessDefinitionEntity processDefinition =
          deploymentCache.findDeployedProcessDefinitionById(processDefinitionId);
      if (processDefinition == null) {
        LOGGER.log(
            Level.FINE,
            "Found event subscription with {0} but process definition {1} could not be found.",
            new Object[] {messageEventSubscription, processDefinitionId});
        return null;

      } else {
        return MessageCorrelationResult.matchedProcessDefinition(
            processDefinition, messageEventSubscription.getActivityId());
      }
    }
  }
 /** @return true if the passed-in user is currently authenticated */
 protected boolean isAuthenticatedUser(UserEntity user) {
   if (user.getId() == null) {
     return false;
   }
   return user.getId()
       .equals(
           org.camunda.bpm.engine.impl.context.Context.getCommandContext()
               .getAuthenticatedUserId());
 }
  protected void deleteTask(String taskId) {
    TaskEntity task = Context.getCommandContext().getTaskManager().findTaskById(taskId);

    if (task != null) {
      if (task.getExecutionId() != null) {
        throw new ProcessEngineException(
            "The task cannot be deleted because is part of a running process");
      }

      String reason =
          (deleteReason == null || deleteReason.length() == 0)
              ? TaskEntity.DELETE_REASON_DELETED
              : deleteReason;
      task.delete(reason, cascade);
    } else if (cascade) {
      Context.getCommandContext()
          .getHistoricTaskInstanceManager()
          .deleteHistoricTaskInstanceById(taskId);
    }
  }
 protected String getDnForUser(String userId) {
   LdapUserEntity user =
       (LdapUserEntity)
           createUserQuery(org.camunda.bpm.engine.impl.context.Context.getCommandContext())
               .userId(userId)
               .singleResult();
   if (user == null) {
     return "";
   } else {
     return user.getDn();
   }
 }
 protected String getDnForGroup(String groupId) {
   LdapGroupEntity group =
       (LdapGroupEntity)
           createGroupQuery(org.camunda.bpm.engine.impl.context.Context.getCommandContext())
               .groupId(groupId)
               .singleResult();
   if (group == null) {
     return "";
   } else {
     return group.getDn();
   }
 }
  public void deleteByteArrayValue() {
    if (byteArrayId != null) {
      // the next apparently useless line is probably to ensure consistency in the DbSqlSession
      // cache,
      // but should be checked and docked here (or removed if it turns out to be unnecessary)
      getByteArrayValue();

      Context.getCommandContext().getByteArrayManager().deleteByteArrayById(this.byteArrayId);

      byteArrayId = null;
    }
  }
  /** customized insert behavior for HistoricVariableUpdateEventEntity */
  protected void insertHistoricVariableUpdateEntity(
      HistoricVariableUpdateEventEntity historyEvent) {
    DbSqlSession dbSqlSession = getDbSqlSession();

    // insert update only if history level = FULL
    int historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel();
    if (historyLevel == ProcessEngineConfigurationImpl.HISTORYLEVEL_FULL) {

      // insert byte array entity (if applicable)
      byte[] byteValue = historyEvent.getByteValue();
      if (byteValue != null) {
        ByteArrayEntity byteArrayEntity =
            new ByteArrayEntity(historyEvent.getVariableName(), byteValue);
        Context.getCommandContext().getDbSqlSession().insert(byteArrayEntity);
        historyEvent.setByteArrayId(byteArrayEntity.getId());
      }
      dbSqlSession.insert(historyEvent);
    }

    // always insert/update HistoricProcessVariableInstance
    if (HistoryEvent.VARIABLE_EVENT_TYPE_CREATE.equals(historyEvent.getEventType())) {
      HistoricVariableInstanceEntity persistentObject =
          new HistoricVariableInstanceEntity(historyEvent);
      dbSqlSession.insert(persistentObject);

    } else if (HistoryEvent.VARIABLE_EVENT_TYPE_UPDATE.equals(historyEvent.getEventType())) {
      HistoricVariableInstanceEntity historicVariableInstanceEntity =
          dbSqlSession.selectById(
              HistoricVariableInstanceEntity.class, historyEvent.getVariableInstanceId());
      historicVariableInstanceEntity.updateFromEvent(historyEvent);

    } else if (HistoryEvent.VARIABLE_EVENT_TYPE_DELETE.equals(historyEvent.getEventType())) {
      HistoricVariableInstanceEntity historicVariableInstanceEntity =
          dbSqlSession.selectById(
              HistoricVariableInstanceEntity.class, historyEvent.getVariableInstanceId());
      if (historicVariableInstanceEntity != null) {
        historicVariableInstanceEntity.delete();
      }
    }
  }
  protected void invokeVariableListeners(boolean includeCustomerListeners) {
    Queue<VariableEvent> variableEventsQueue = getVariableEventQueue();

    while (!variableEventsQueue.isEmpty()) {
      // do not remove the event yet, as otherwise new events will immediately be dispatched
      VariableEvent nextEvent = variableEventsQueue.peek();

      CmmnExecution sourceExecution = (CmmnExecution) nextEvent.getSourceScope();

      DelegateCaseVariableInstanceImpl delegateVariable =
          DelegateCaseVariableInstanceImpl.fromVariableInstance(nextEvent.getVariableInstance());
      delegateVariable.setEventName(nextEvent.getEventName());
      delegateVariable.setSourceExecution(sourceExecution);

      Map<String, List<VariableListener<?>>> listenersByActivity =
          sourceExecution
              .getActivity()
              .getVariableListeners(delegateVariable.getEventName(), includeCustomerListeners);

      CmmnExecution currentExecution = sourceExecution;
      while (currentExecution != null) {

        if (currentExecution.getActivityId() != null) {
          List<VariableListener<?>> listeners =
              listenersByActivity.get(currentExecution.getActivityId());

          if (listeners != null) {
            delegateVariable.setScopeExecution(currentExecution);

            for (VariableListener<?> listener : listeners) {
              try {
                CaseVariableListener caseVariableListener = (CaseVariableListener) listener;
                CaseVariableListenerInvocation invocation =
                    new CaseVariableListenerInvocation(
                        caseVariableListener, delegateVariable, currentExecution);
                Context.getProcessEngineConfiguration()
                    .getDelegateInterceptor()
                    .handleInvocation(invocation);
              } catch (Exception e) {
                throw LOG.invokeVariableListenerException(e);
              }
            }
          }
        }

        currentExecution = currentExecution.getParent();
      }

      // finally remove the event from the queue
      variableEventsQueue.remove();
    }
  }
  // variable listeners
  public void dispatchEvent(VariableEvent variableEvent) {
    boolean invokeCustomListeners =
        Context.getProcessEngineConfiguration().isInvokeCustomVariableListeners();

    Map<String, List<VariableListener<?>>> listeners =
        getActivity().getVariableListeners(variableEvent.getEventName(), invokeCustomListeners);

    // only attempt to invoke listeners if there are any (as this involves resolving the upwards
    // execution hierarchy)
    if (!listeners.isEmpty()) {
      getCaseInstance().queueVariableEvent(variableEvent, invokeCustomListeners);
    }
  }
 public ProcessDefinitionEntity findDeployedLatestProcessDefinitionByKey(
     String processDefinitionKey) {
   ProcessDefinitionEntity processDefinition =
       Context.getCommandContext()
           .getProcessDefinitionManager()
           .findLatestProcessDefinitionByKey(processDefinitionKey);
   if (processDefinition == null) {
     throw new ProcessEngineException(
         "no processes deployed with key '" + processDefinitionKey + "'");
   }
   processDefinition = resolveProcessDefinition(processDefinition);
   return processDefinition;
 }
  public TaskEntity createTask(TaskDecorator taskDecorator) {
    TaskEntity task = TaskEntity.createAndInsert(this);

    setTask(task);

    taskDecorator.decorate(task, this);

    Context.getCommandContext().getHistoricTaskInstanceManager().createHistoricTask(task);

    // All properties set, now firing 'create' event
    task.fireEvent(TaskListener.EVENTNAME_CREATE);

    return task;
  }
  public Void execute(CommandContext commandContext) {

    if (deploymentIds == null) {
      throw new ProcessEngineException("Deployment Ids cannot be null.");
    }

    commandContext.getAuthorizationManager().isCamundaAdmin();

    Context.getProcessEngineConfiguration()
        .getProcessApplicationManager()
        .unregisterProcessApplicationForDeployments(deploymentIds, removeProcessesFromCache);

    return null;
  }
  public DecisionRequirementsDefinition execute(CommandContext commandContext) {
    ensureNotNull("decisionRequirementsDefinitionId", decisionRequirementsDefinitionId);
    DeploymentCache deploymentCache = Context.getProcessEngineConfiguration().getDeploymentCache();
    DecisionRequirementsDefinitionEntity decisionRequirementsDefinition =
        deploymentCache.findDeployedDecisionRequirementsDefinitionById(
            decisionRequirementsDefinitionId);

    for (CommandChecker checker :
        commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
      checker.checkReadDecisionRequirementsDefinition(decisionRequirementsDefinition);
    }

    return decisionRequirementsDefinition;
  }
  protected Integer getJobDefinitionPriority(
      ExecutionEntity execution, JobDeclaration<?> jobDeclaration) {
    String jobDefinitionId = jobDeclaration.getJobDefinitionId();

    if (jobDefinitionId != null) {
      JobDefinitionEntity jobDefinition =
          Context.getCommandContext().getJobDefinitionManager().findById(jobDefinitionId);

      if (jobDefinition != null) {
        return jobDefinition.getJobPriority();
      }
    }

    return null;
  }
  public UserOperationLogContextEntryBuilder inContextOf(JobDefinitionEntity jobDefinition) {
    entry.setJobDefinitionId(jobDefinition.getId());
    entry.setProcessDefinitionId(jobDefinition.getProcessDefinitionId());
    entry.setProcessDefinitionKey(jobDefinition.getProcessDefinitionKey());

    if (jobDefinition.getProcessDefinitionId() != null) {
      ProcessDefinitionEntity processDefinition =
          Context.getProcessEngineConfiguration()
              .getDeploymentCache()
              .findDeployedProcessDefinitionById(jobDefinition.getProcessDefinitionId());
      entry.setDeploymentId(processDefinition.getDeploymentId());
    }

    return this;
  }
 public ProcessDefinitionEntity findDeployedProcessDefinitionById(String processDefinitionId) {
   if (processDefinitionId == null) {
     throw new ProcessEngineException("Invalid process definition id : null");
   }
   ProcessDefinitionEntity processDefinition =
       Context.getCommandContext()
           .getProcessDefinitionManager()
           .findLatestProcessDefinitionById(processDefinitionId);
   if (processDefinition == null) {
     throw new ProcessEngineException(
         "no deployed process definition found with id '" + processDefinitionId + "'");
   }
   processDefinition = resolveProcessDefinition(processDefinition);
   return processDefinition;
 }
  public void setByteArrayValue(byte[] bytes) {
    deleteByteArrayValue();

    ByteArrayEntity byteArrayValue = null;
    if (bytes != null) {
      byteArrayValue = new ByteArrayEntity(valueFields.getName(), bytes);
      Context.getCommandContext().getDbEntityManager().insert(byteArrayValue);
    }

    this.byteArrayValue = byteArrayValue;

    if (byteArrayValue != null) {
      this.byteArrayId = byteArrayValue.getId();
    } else {
      this.byteArrayId = null;
    }
  }
 public ProcessDefinitionEntity findDeployedProcessDefinitionByKeyAndVersion(
     String processDefinitionKey, Integer processDefinitionVersion) {
   ProcessDefinitionEntity processDefinition =
       (ProcessDefinitionEntity)
           Context.getCommandContext()
               .getProcessDefinitionManager()
               .findProcessDefinitionByKeyAndVersion(
                   processDefinitionKey, processDefinitionVersion);
   if (processDefinition == null) {
     throw new ProcessEngineException(
         "no processes deployed with key = '"
             + processDefinitionKey
             + "' and version = '"
             + processDefinitionVersion
             + "'");
   }
   processDefinition = resolveProcessDefinition(processDefinition);
   return processDefinition;
 }
  public void removeDeployment(String deploymentId) {
    // remove all process definitions for a specific deployment
    List<ProcessDefinition> allDefinitionsForDeployment =
        new ProcessDefinitionQueryImpl(Context.getCommandContext())
            .deploymentId(deploymentId)
            .list();
    for (ProcessDefinition processDefinition : allDefinitionsForDeployment) {
      try {
        removeProcessDefinition(processDefinition.getId());

      } catch (Exception e) {
        LOGGER.log(
            Level.WARNING,
            "Could not remove process definition with id '"
                + processDefinition.getId()
                + "' from the cache.",
            e);
      }
    }
  }
  public Void migrateProcessInstance(CommandContext commandContext, String processInstanceId) {

    ExecutionEntity processInstance =
        commandContext.getExecutionManager().findExecutionById(processInstanceId);

    ProcessDefinitionEntity targetProcessDefinition =
        Context.getProcessEngineConfiguration()
            .getDeploymentCache()
            .findDeployedProcessDefinitionById(migrationPlan.getTargetProcessDefinitionId());

    // Initialize migration: match migration instructions to activity instances and collect required
    // entities
    MigratingProcessInstance migratingProcessInstance =
        MigratingProcessInstance.initializeFrom(
            commandContext, migrationPlan, processInstance, targetProcessDefinition);

    validateInstructions(migratingProcessInstance);

    migrateProcessInstance(migratingProcessInstance);

    return null;
  }
  public ProcessDefinitionEntity resolveProcessDefinition(
      ProcessDefinitionEntity processDefinition) {
    String processDefinitionId = processDefinition.getId();
    String deploymentId = processDefinition.getDeploymentId();
    processDefinition = processDefinitionCache.get(processDefinitionId);
    if (processDefinition == null) {
      DeploymentEntity deployment =
          Context.getCommandContext().getDeploymentManager().findDeploymentById(deploymentId);
      deployment.setNew(false);
      deploy(deployment);
      processDefinition = processDefinitionCache.get(processDefinitionId);

      if (processDefinition == null) {
        throw new ProcessEngineException(
            "deployment '"
                + deploymentId
                + "' didn't put process definition '"
                + processDefinitionId
                + "' in the cache");
      }
    }
    return processDefinition;
  }
  protected ActivityImpl getCurrentActivity(CommandContext commandContext, JobEntity job) {
    String type = job.getJobHandlerType();
    ActivityImpl activity = null;

    String configuration = job.getJobHandlerConfiguration();

    if (TimerExecuteNestedActivityJobHandler.TYPE.equals(type)
        || TimerCatchIntermediateEventJobHandler.TYPE.equals(type)) {
      ExecutionEntity execution = fetchExecutionEntity(job.getExecutionId());
      if (execution != null) {
        String acitivtyId = TimerEventJobHandler.getKey(configuration);
        activity = execution.getProcessDefinition().findActivity(acitivtyId);
      }

    } else if (TimerStartEventJobHandler.TYPE.equals(type)) {
      DeploymentCache deploymentCache =
          Context.getProcessEngineConfiguration().getDeploymentCache();
      String definitionKey = TimerEventJobHandler.getKey(configuration);
      ProcessDefinitionEntity processDefinition =
          deploymentCache.findDeployedLatestProcessDefinitionByKey(definitionKey);
      if (processDefinition != null) {
        activity = processDefinition.getInitial();
      }

    } else if (AsyncContinuationJobHandler.TYPE.equals(type)) {
      ExecutionEntity execution = fetchExecutionEntity(job.getExecutionId());
      if (execution != null) {
        activity = execution.getActivity();
      }

    } else {
      // noop, because activity type is not supported
    }

    return activity;
  }
  public Void execute(final CommandContext commandContext) {
    ensureAtLeastOneNotNull(
        "At least one of the following correlation criteria has to be present: "
            + "messageName, businessKey, correlationKeys, processInstanceId",
        messageName,
        builder.getBusinessKey(),
        builder.getCorrelationProcessInstanceVariables(),
        builder.getProcessInstanceId());

    final CorrelationHandler correlationHandler =
        Context.getProcessEngineConfiguration().getCorrelationHandler();
    final CorrelationSet correlationSet = new CorrelationSet(builder);
    List<MessageCorrelationResult> correlationResults =
        commandContext.runWithoutAuthorization(
            new Callable<List<MessageCorrelationResult>>() {
              public List<MessageCorrelationResult> call() throws Exception {
                return correlationHandler.correlateMessages(
                    commandContext, messageName, correlationSet);
              }
            });

    // check authorization
    for (MessageCorrelationResult correlationResult : correlationResults) {
      checkAuthorization(correlationResult);
    }

    for (MessageCorrelationResult correlationResult : correlationResults) {
      if (MessageCorrelationResult.TYPE_EXECUTION.equals(correlationResult.getResultType())) {
        triggerExecution(commandContext, correlationResult);
      } else {
        instantiateProcess(commandContext, correlationResult);
      }
    }

    return null;
  }
 public Session openSession() {
   return Context.getCommandContext().getDbSqlSession();
 }
 public void notify(DelegateCaseExecution caseExecution) throws Exception {
   Context.getProcessEngineConfiguration()
       .getScriptingEnvironment()
       .execute(script, caseExecution);
 }