Search code examples
javabpmncamunda

Camunda set tenant id when starting a shared process definition


Is it possible to set a tenant id when the process definition itself is shared between multiple tenants?

I call this method where I get both id's from the http request which in turn I pass to the embedded process-engine

public void startInstance(String processDefinitionId, String tenantId) {
        this.runtimeService.startProcessInstanceById(processDefinitionId);
    }

But using this method I am not able to pass a tenant id to the process instance. How do I achieve this?

I found this reading: https://docs.camunda.org/manual/7.5/user-guide/process-engine/multi-tenancy/#instantiate-a-shared-definition but it does not really solve my problem since I get the tenant id from an http-header.


Solution

  • Thanks to the comment of Jan I figured out that one could add the tenant id as a variable to the started instance and retrieve it in the TenantProvider.

    The code looks like this

    runtimeService.createProcessInstanceById(processDefinitionId).setVariable("tenantId", tenantId).execute();
    

    And on your TenantProvider simply get this variable like so

    public class TenantProvider implements TenantIdProvider {
    
        @Override
        public String provideTenantIdForProcessInstance(TenantIdProviderProcessInstanceContext ctx) {
            return (String) ctx.getVariables().get("tenantId");
        }
    
        @Override
        public String provideTenantIdForCaseInstance(TenantIdProviderCaseInstanceContext ctx) {
            return (String) ctx.getVariables().get("tenantId");
        }
    
        @Override
        public String provideTenantIdForHistoricDecisionInstance(TenantIdProviderHistoricDecisionInstanceContext ctx) {
            return (String) ctx.getExecution().getVariable("tenantId");
        }
    }
    

    To enable the use of a TenantProvider, start your engine like so

    ProcessEngine engine = new StandaloneProcessEngineConfiguration()
                    .setTenantIdProvider(new TenantProvider())
                    ...
                    .buildProcessEngine();