Context.getCommandContext vs. commandExecutor.execute()

I wonder if there is any structural difference between

Command/Executor

Context.getProcessEngineConfiguration().getCommandExecutorTxRequired().execute(new Command<Void>() {
    @Override
    public Void execute(CommandContext commandContext) {
        commandContext.getOperationLogManager().logUserOperations(context);
        return null;
    }
});

and

getCommandContext

Context.getCommandContext()
        .getOperationLogManager()
        .logUserOperations(context);

or are both synonym?

1 Like

Hi Jan,

Context.getCommandContext is a shorthand to access the command context at any place without passing it on. This requires the code to be executed within an active command, or else the method returns null.

To be precise, your code snippets are not equivalent because snippet 2 is not executed within a command. Given an active command, these are equivalent

commandContext.getOperationLogManager().logUserOperations(context);

and

Context.getCommandContext().getOperationLogManager().logUserOperations(context);

Cheers,
Thorben

1 Like

I see … I found out that both behave the same when I use them inside a HistoryEventHandler. I guess thats because the handler itself is executed in a commandContext.

Hi Thorben,

I am getting Context.getCommandContext() as null in my custom task listeners, what could be possible reason and how to correct it

  val timer = new TimerEntity
  timer.setExecution(execution)
  timer.setDuedate(delegateTask.getDueDate)
  timer.setJobHandlerType(UserTaskOverdueJobHandler.USER_TASK_ESCALATION_JOB_HANDLER_TYPE)
  timer.setProcessDefinitionKey(processDefinition.getKey)
  timer.setDeploymentId(processDefinition.getDeploymentId)
  timer.setJobHandlerConfigurationRaw(extraParams.asJson)

Context.getCommandContext().getJobManager().schedule(timer);

Has anyone found a way to use Context methods outside of a command without getting null? I want to use the DeploymentCache to get a process definition using the following snippet:

ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
ProcessEngineConfigurationImpl config = (ProcessEngineConfigurationImpl)engine.getProcessEngineConfiguration();
Context.setCommandContext(new CommandContext(config));
DeploymentCache deploymentCache = config.getDeploymentCache();
ProcessDefinitionEntity processDefinition = deploymentCache.findDeployedProcessDefinitionById(someDefinitionId);

However, processDefinition is always null even though the definition with the given id exists. Any thoughts?

Unless you really understand the concepts, don’t use the CommandContext classes etc. You will not enjoy that :slight_smile:

Why don’t you use RepositoryService#getProcessDefinition instead? This does pretty much exactly the thing you are trying to do.

i’d like use this method to preloading resources to cache