This is an automated email from the ASF dual-hosted git repository.

yesamer pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-kie.git


The following commit(s) were added to refs/heads/main by this push:
     new 202f03fd9ed [incubator-kie#2421] Support variable migration rules in 
process migration plans (.mpf) (#7259)
202f03fd9ed is described below

commit 202f03fd9edd0225f489f33368f6ea99678de225
Author: Mohammad Mustafa <[email protected]>
AuthorDate: Sat Nov 28 10:26:55 2026 +0300

    [incubator-kie#2421] Support variable migration rules in process migration 
plans (.mpf) (#7259)
    
    * [incubator-kie-issues#2421] Support variable migration rules in migration 
plans
    
    * [incubator-kie-issues#2421] Address review comments on variable migration
    
    - Fire variable changed events so data-index and data-audit are updated
    - Skip variable rules when the instance has no variable scope
    - Reject rename rules where from and to are the same
    - Log a warning when rename overwrites an existing value
    - Fail migration when a value does not match the target variable type
    - Keep the original cause in MigrationPlanFileFormatException
    - Document that rename/remove keep the variable key with a null value
---
 .rat-excludes                                      |   1 +
 .../flow/migration/MigrationPlanProviderTest.java  |  52 ++++++-
 .../flow/migration/MigrationPlanServiceTest.java   | 155 +++++++++++++++++++++
 .../META-INF/migration-plan/variable_migration.mpf |  35 +++++
 .../MigrationPlanFileFormatException.java          |   2 +-
 .../jbpm/flow/migration/MigrationPlanService.java  |   9 ++
 .../org/jbpm/flow/migration/VariableMigrator.java  | 147 +++++++++++++++++++
 .../impl/JsonMigrationPlanFileReader.java          |   6 +
 .../model/ProcessInstanceMigrationPlan.java        |  16 ++-
 .../VariableMigrationAction.java}                  |  33 +++--
 .../migration/model/VariableMigrationPlan.java     | 154 ++++++++++++++++++++
 ...MigrationProcessInstanceMarshallerListener.java |   2 +-
 12 files changed, 596 insertions(+), 16 deletions(-)

diff --git a/.rat-excludes b/.rat-excludes
index e8d8ad5827a..6cd47468fbb 100644
--- a/.rat-excludes
+++ b/.rat-excludes
@@ -2334,6 +2334,7 @@ 
kogito-addons/common/persistence/postgresql/src/main/resources/META-INF/kogito.a
 
kogito-addons/common/persistence/rocksdb/src/main/resources/META-INF/kogito.addon
 
kogito-addons/common/process-instance-migration/src/test/resources/META-INF/migration-plan/simple_migration.mpf
 
kogito-addons/common/process-instance-migration/src/test/resources/META-INF/migration-plan/simple_migration_version.mpf
+kogito-addons/common/process-instance-migration/src/test/resources/META-INF/migration-plan/variable_migration.mpf
 
kogito-api/kogito-events-core/src/main/resources/META-INF/services/com.fasterxml.jackson.databind.Module
 
kogito-api/kogito-events-core/src/main/resources/META-INF/services/org.kie.kogito.event.impl.adapter.DataEventAdapter
 
kogito-drools/kogito-pmml/src/test/resources/org/kie/kogito/pmml/test_regression.pmml
diff --git 
a/kogito-addons/common/process-instance-migration/src/test/java/org/jbpm/flow/migration/MigrationPlanProviderTest.java
 
b/kogito-addons/common/process-instance-migration/src/test/java/org/jbpm/flow/migration/MigrationPlanProviderTest.java
index d417066b969..2f75073a7e0 100644
--- 
a/kogito-addons/common/process-instance-migration/src/test/java/org/jbpm/flow/migration/MigrationPlanProviderTest.java
+++ 
b/kogito-addons/common/process-instance-migration/src/test/java/org/jbpm/flow/migration/MigrationPlanProviderTest.java
@@ -18,17 +18,23 @@
  */
 package org.jbpm.flow.migration;
 
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
 import java.util.List;
 
+import org.jbpm.flow.migration.impl.JsonMigrationPlanFileReader;
 import org.jbpm.flow.migration.model.MigrationPlan;
 import org.jbpm.flow.migration.model.NodeInstanceMigrationPlan;
 import org.jbpm.flow.migration.model.ProcessDefinitionMigrationPlan;
 import org.jbpm.flow.migration.model.ProcessInstanceMigrationPlan;
+import org.jbpm.flow.migration.model.VariableMigrationAction;
+import org.jbpm.flow.migration.model.VariableMigrationPlan;
 import org.jbpm.ruleflow.core.WorkflowElementIdentifierFactory;
 import org.junit.jupiter.api.Test;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
 public class MigrationPlanProviderTest {
 
@@ -55,9 +61,53 @@ public class MigrationPlanProviderTest {
         plan.setProcessMigrationPlan(pdmp);
 
         assertThat(plans)
-                .hasSize(2)
+                .hasSize(3)
                 .contains(plan);
 
     }
 
+    @Test
+    public void testReadingVariableMigrationPlan() {
+        MigrationPlanProvider provider = 
MigrationPlanProvider.newMigrationPlanProviderBuilder().withEnvironmentDefaults().build();
+        List<MigrationPlan> plans = provider.findMigrationPlans();
+
+        MigrationPlan plan = plans.stream()
+                .filter(p -> "my variable migration".equals(p.getName()))
+                .findFirst()
+                .orElseThrow();
+
+        
assertThat(plan.getProcessMigrationPlan().getVariableMigrationPlan()).containsExactly(
+                new VariableMigrationPlan(VariableMigrationAction.RENAME, 
null, "custName", "customerName", null),
+                new VariableMigrationPlan(VariableMigrationAction.DEFAULT, 
"riskLevel", null, null, "LOW"),
+                new VariableMigrationPlan(VariableMigrationAction.DEFAULT, 
"approvedBy", null, null, "SYSTEM"),
+                new VariableMigrationPlan(VariableMigrationAction.REMOVE, 
"tempFlag", null, null, null));
+    }
+
+    @Test
+    public void testReadingVariableMigrationPlanWithoutRequiredField() {
+        String json = "{ \"processMigrationPlan\" : { 
\"variableMigrationPlan\" : [ { \"action\" : \"rename\", \"from\" : 
\"custName\" } ] } }";
+
+        assertThatThrownBy(() -> new JsonMigrationPlanFileReader().read(new 
ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))))
+                .isInstanceOf(MigrationPlanFileFormatException.class)
+                .hasMessageContaining("requires field to");
+    }
+
+    @Test
+    public void testReadingVariableMigrationPlanRenamingToItself() {
+        String json = "{ \"processMigrationPlan\" : { 
\"variableMigrationPlan\" : [ { \"action\" : \"rename\", \"from\" : 
\"custName\", \"to\" : \"custName\" } ] } }";
+
+        assertThatThrownBy(() -> new JsonMigrationPlanFileReader().read(new 
ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))))
+                .isInstanceOf(MigrationPlanFileFormatException.class)
+                .hasMessageContaining("renames a variable to itself")
+                .hasCauseInstanceOf(IllegalArgumentException.class);
+    }
+
+    @Test
+    public void testReadingVariableMigrationPlanWithUnknownAction() {
+        String json = "{ \"processMigrationPlan\" : { 
\"variableMigrationPlan\" : [ { \"action\" : \"copy\", \"name\" : \"custName\" 
} ] } }";
+
+        assertThatThrownBy(() -> new JsonMigrationPlanFileReader().read(new 
ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))))
+                .isInstanceOf(MigrationPlanFileFormatException.class);
+    }
+
 }
diff --git 
a/kogito-addons/common/process-instance-migration/src/test/java/org/jbpm/flow/migration/MigrationPlanServiceTest.java
 
b/kogito-addons/common/process-instance-migration/src/test/java/org/jbpm/flow/migration/MigrationPlanServiceTest.java
index 2df1b83775f..ad55922f2bd 100644
--- 
a/kogito-addons/common/process-instance-migration/src/test/java/org/jbpm/flow/migration/MigrationPlanServiceTest.java
+++ 
b/kogito-addons/common/process-instance-migration/src/test/java/org/jbpm/flow/migration/MigrationPlanServiceTest.java
@@ -20,18 +20,33 @@ package org.jbpm.flow.migration;
 
 import java.util.Collections;
 
+import org.jbpm.process.core.context.variable.Variable;
+import org.jbpm.process.core.context.variable.VariableScope;
+import org.jbpm.process.core.datatype.impl.type.ObjectDataType;
+import org.jbpm.process.instance.context.variable.VariableScopeInstance;
+import org.jbpm.ruleflow.core.RuleFlowProcess;
 import org.jbpm.ruleflow.instance.RuleFlowProcessInstance;
+import org.jbpm.workflow.core.impl.WorkflowProcessImpl;
 import org.jbpm.workflow.instance.impl.ExtendedNodeInstanceImpl;
 import org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.TestInstance;
 import org.junit.jupiter.api.TestInstance.Lifecycle;
+import org.kie.kogito.internal.process.event.KogitoProcessEventSupport;
+import org.kie.kogito.internal.process.runtime.KogitoProcessRuntime;
 import org.kie.kogito.process.Processes;
 import org.mockito.Mockito;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static 
org.jbpm.ruleflow.core.WorkflowElementIdentifierFactory.fromExternalFormat;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 @TestInstance(Lifecycle.PER_CLASS)
@@ -121,6 +136,146 @@ public class MigrationPlanServiceTest {
                 .hasFieldOrPropertyWithValue("processVersion", "3");
     }
 
+    @Test
+    public void testMigrationProcessInstanceVariables() {
+        MigrationPlanService service = new MigrationPlanService();
+
+        RuleFlowProcessInstance processImpl = new RuleFlowProcessInstance();
+        processImpl.setInternalProcess(new DummyProcess("process_B", "2"));
+        processImpl.setProcessId("process_E");
+        processImpl.setProcessVersion("1");
+        VariableScopeInstance variableScope = new VariableScopeInstance();
+        processImpl.setContextInstance(VariableScope.VARIABLE_SCOPE, 
variableScope);
+        variableScope.internalSetVariable("custName", "John");
+        variableScope.internalSetVariable("approvedBy", "manager");
+        variableScope.internalSetVariable("tempFlag", Boolean.TRUE);
+
+        service.migrateProcessElement(processes, processImpl);
+
+        assertThat(processImpl)
+                .hasFieldOrPropertyWithValue("processId", "process_B")
+                .hasFieldOrPropertyWithValue("processVersion", "2");
+        assertThat(variableScope.getVariables())
+                .containsEntry("customerName", "John")
+                .containsEntry("custName", null)
+                .containsEntry("riskLevel", "LOW")
+                .containsEntry("approvedBy", "manager")
+                .containsEntry("tempFlag", null);
+    }
+
+    @Test
+    public void testMigrationProcessInstanceRenameMissingVariable() {
+        MigrationPlanService service = new MigrationPlanService();
+
+        RuleFlowProcessInstance processImpl = new RuleFlowProcessInstance();
+        processImpl.setInternalProcess(new DummyProcess("process_B", "2"));
+        processImpl.setProcessId("process_E");
+        processImpl.setProcessVersion("1");
+        VariableScopeInstance variableScope = new VariableScopeInstance();
+        processImpl.setContextInstance(VariableScope.VARIABLE_SCOPE, 
variableScope);
+        variableScope.internalSetVariable("customerName", "Jane");
+
+        service.migrateProcessElement(processes, processImpl);
+
+        assertThat(variableScope.getVariables())
+                .containsEntry("customerName", "Jane")
+                .doesNotContainKey("custName");
+    }
+
+    @Test
+    public void testMigrationProcessInstanceRenameOverwritesTarget() {
+        MigrationPlanService service = new MigrationPlanService();
+
+        RuleFlowProcessInstance processImpl = newProcessInstanceToMigrate(new 
DummyProcess("process_B", "2"));
+        VariableScopeInstance variableScope = (VariableScopeInstance) 
processImpl.getContextInstance(VariableScope.VARIABLE_SCOPE);
+        variableScope.internalSetVariable("custName", "John");
+        variableScope.internalSetVariable("customerName", "Jane");
+
+        service.migrateProcessElement(processes, processImpl);
+
+        assertThat(variableScope.getVariables())
+                .containsEntry("customerName", "John")
+                .containsEntry("custName", null);
+    }
+
+    @Test
+    public void testMigrationProcessInstanceVariablesFireEvents() {
+        MigrationPlanService service = new MigrationPlanService();
+        KogitoProcessEventSupport events = 
Mockito.mock(KogitoProcessEventSupport.class);
+        KogitoProcessRuntime runtime = 
Mockito.mock(KogitoProcessRuntime.class);
+        when(runtime.getProcessEventSupport()).thenReturn(events);
+
+        RuleFlowProcessInstance processImpl = newProcessInstanceToMigrate(new 
DummyProcess("process_B", "2"));
+        VariableScopeInstance variableScope = (VariableScopeInstance) 
processImpl.getContextInstance(VariableScope.VARIABLE_SCOPE);
+        variableScope.internalSetVariable("custName", "John");
+        variableScope.internalSetVariable("approvedBy", "manager");
+        variableScope.internalSetVariable("tempFlag", Boolean.TRUE);
+
+        service.migrateProcessElement(runtime, processes, processImpl);
+
+        verifyVariableChanged(events, processImpl, "customerName", null, 
"John");
+        verifyVariableChanged(events, processImpl, "custName", "John", null);
+        verifyVariableChanged(events, processImpl, "riskLevel", null, "LOW");
+        verifyVariableChanged(events, processImpl, "tempFlag", Boolean.TRUE, 
null);
+        verify(events, never()).fireAfterVariableChanged(eq("approvedBy"), 
any(), any(), any(), any(), any(), any(), any());
+    }
+
+    @Test
+    public void testMigrationProcessInstanceVariableTypeMismatch() {
+        MigrationPlanService service = new MigrationPlanService();
+
+        RuleFlowProcess targetProcess = new RuleFlowProcess();
+        targetProcess.setId("process_B");
+        targetProcess.setVersion("2");
+        Variable riskLevel = new Variable();
+        riskLevel.setName("riskLevel");
+        riskLevel.setType(new ObjectDataType(Integer.class));
+        targetProcess.getVariableScope().addVariable(riskLevel);
+
+        RuleFlowProcessInstance processImpl = 
newProcessInstanceToMigrate(targetProcess);
+
+        assertThatThrownBy(() -> service.migrateProcessElement(processes, 
processImpl))
+                .isInstanceOf(IllegalArgumentException.class)
+                .hasMessageContaining("riskLevel")
+                .hasMessageContaining(Integer.class.getName());
+    }
+
+    @Test
+    public void testMigrationProcessInstanceWithoutVariableScope() {
+        MigrationPlanService service = new MigrationPlanService();
+
+        // definition without a variable scope
+        WorkflowProcessImpl targetProcess = new WorkflowProcessImpl();
+        targetProcess.setId("process_B");
+        targetProcess.setVersion("2");
+
+        RuleFlowProcessInstance processImpl = new RuleFlowProcessInstance();
+        processImpl.setInternalProcess(targetProcess);
+        processImpl.setProcessId("process_E");
+        processImpl.setProcessVersion("1");
+
+        service.migrateProcessElement(processes, processImpl);
+
+        
assertThat(processImpl.getContextInstance(VariableScope.VARIABLE_SCOPE)).isNull();
+        assertThat(processImpl)
+                .hasFieldOrPropertyWithValue("processId", "process_B")
+                .hasFieldOrPropertyWithValue("processVersion", "2");
+    }
+
+    private static RuleFlowProcessInstance 
newProcessInstanceToMigrate(org.kie.api.definition.process.Process 
targetProcess) {
+        RuleFlowProcessInstance processImpl = new RuleFlowProcessInstance();
+        processImpl.setInternalProcess(targetProcess);
+        processImpl.setProcessId("process_E");
+        processImpl.setProcessVersion("1");
+        processImpl.setContextInstance(VariableScope.VARIABLE_SCOPE, new 
VariableScopeInstance());
+        return processImpl;
+    }
+
+    private static void verifyVariableChanged(KogitoProcessEventSupport 
events, RuleFlowProcessInstance processImpl, String name, Object oldValue, 
Object newValue) {
+        verify(events).fireBeforeVariableChanged(eq(name), eq(name), 
eq(oldValue), eq(newValue), any(), same(processImpl), isNull(), any());
+        verify(events).fireAfterVariableChanged(eq(name), eq(name), 
eq(oldValue), eq(newValue), any(), same(processImpl), isNull(), any());
+    }
+
     @Test
     public void testMigrationNode() {
         MigrationPlanService service = new MigrationPlanService();
diff --git 
a/kogito-addons/common/process-instance-migration/src/test/resources/META-INF/migration-plan/variable_migration.mpf
 
b/kogito-addons/common/process-instance-migration/src/test/resources/META-INF/migration-plan/variable_migration.mpf
new file mode 100644
index 00000000000..877fde8a04c
--- /dev/null
+++ 
b/kogito-addons/common/process-instance-migration/src/test/resources/META-INF/migration-plan/variable_migration.mpf
@@ -0,0 +1,35 @@
+{
+    "name" : "my variable migration",
+    "processMigrationPlan" : {
+        "sourceProcessDefinition" : {
+            "processId" : "process_E",
+            "processVersion" : "1"
+        },
+        "targetProcessDefinition" : {
+            "processId" : "process_B",
+            "processVersion" : "2"
+        },
+        "nodeInstanceMigrationPlan" : [],
+        "variableMigrationPlan" : [
+            {
+                "action" : "rename",
+                "from" : "custName",
+                "to" : "customerName"
+            },
+            {
+                "action" : "default",
+                "name" : "riskLevel",
+                "value" : "LOW"
+            },
+            {
+                "action" : "default",
+                "name" : "approvedBy",
+                "value" : "SYSTEM"
+            },
+            {
+                "action" : "remove",
+                "name" : "tempFlag"
+            }
+        ]
+    }
+}
diff --git 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/MigrationPlanFileFormatException.java
 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/MigrationPlanFileFormatException.java
index a410f821b05..37115185757 100644
--- 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/MigrationPlanFileFormatException.java
+++ 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/MigrationPlanFileFormatException.java
@@ -28,7 +28,7 @@ public class MigrationPlanFileFormatException extends 
IOException {
         super(msg);
     }
 
-    public MigrationPlanFileFormatException(String msg, IOException e) {
+    public MigrationPlanFileFormatException(String msg, Throwable e) {
         super(msg, e);
     }
 
diff --git 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/MigrationPlanService.java
 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/MigrationPlanService.java
index 662eefaf914..94c9b8c3752 100644
--- 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/MigrationPlanService.java
+++ 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/MigrationPlanService.java
@@ -27,6 +27,7 @@ import org.jbpm.ruleflow.instance.RuleFlowProcessInstance;
 import org.jbpm.workflow.instance.impl.NodeInstanceImpl;
 import org.kie.kogito.Model;
 import org.kie.kogito.internal.process.runtime.KogitoNodeInstance;
+import org.kie.kogito.internal.process.runtime.KogitoProcessRuntime;
 import org.kie.kogito.internal.process.runtime.KogitoWorkflowProcessInstance;
 import org.kie.kogito.process.Processes;
 import org.slf4j.Logger;
@@ -57,6 +58,13 @@ public class MigrationPlanService {
     }
 
     public void migrateProcessElement(Processes processes, 
KogitoWorkflowProcessInstance processInstance) {
+        migrateProcessElement(null, processes, processInstance);
+    }
+
+    /**
+     * @param runtime runtime used to fire variable changed events for 
migrated variables; when {@code null} no events are fired
+     */
+    public void migrateProcessElement(KogitoProcessRuntime runtime, Processes 
processes, KogitoWorkflowProcessInstance processInstance) {
         MigrationPlan plan = getMigrationPlan(processes, processInstance);
         if (plan != null) {
             // the process will have to do nothing as it is done by the engine 
itself
@@ -69,6 +77,7 @@ public class MigrationPlanService {
             RuleFlowProcessInstance ruleFlowProcessInstance = 
(RuleFlowProcessInstance) processInstance;
             
ruleFlowProcessInstance.setProcessId(plan.getProcessMigrationPlan().getTargetProcessDefinition().getProcessId());
             
ruleFlowProcessInstance.setProcessVersion(plan.getProcessMigrationPlan().getTargetProcessDefinition().getProcessVersion());
+            VariableMigrator.migrate(runtime, ruleFlowProcessInstance, 
plan.getProcessMigrationPlan().getVariableMigrationPlan());
         } else {
             LOGGER.debug("Process instance {} won't be migrated", 
processInstance);
         }
diff --git 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/VariableMigrator.java
 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/VariableMigrator.java
new file mode 100644
index 00000000000..b9d1f247404
--- /dev/null
+++ 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/VariableMigrator.java
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jbpm.flow.migration;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+import org.jbpm.flow.migration.model.VariableMigrationPlan;
+import org.jbpm.process.core.ContextContainer;
+import org.jbpm.process.core.context.variable.Variable;
+import org.jbpm.process.core.context.variable.VariableScope;
+import org.jbpm.process.instance.context.variable.VariableScopeInstance;
+import org.jbpm.ruleflow.instance.RuleFlowProcessInstance;
+import org.kie.kogito.internal.process.runtime.KogitoProcessRuntime;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Applies the variable migration rules of a migration plan to one process 
instance.
+ * <p>
+ * Each change fires the before / after variable changed events (when a 
runtime is given) so that listeners
+ * such as data-index and data-audit see the migrated values.
+ * <p>
+ * The variable scope has no way to remove an entry, so {@code rename} and 
{@code remove} set the old variable to
+ * {@code null}: the name stays in the variable map with a {@code null} value.
+ */
+final class VariableMigrator {
+
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(VariableMigrator.class);
+
+    private final KogitoProcessRuntime runtime;
+    private final RuleFlowProcessInstance processInstance;
+    private final VariableScopeInstance variables;
+    private final VariableScope targetDefinition;
+
+    private VariableMigrator(KogitoProcessRuntime runtime, 
RuleFlowProcessInstance processInstance, VariableScopeInstance variables) {
+        this.runtime = runtime;
+        this.processInstance = processInstance;
+        this.variables = variables;
+        this.targetDefinition = processInstance.getProcess() instanceof 
ContextContainer
+                ? (VariableScope) ((ContextContainer) 
processInstance.getProcess()).getDefaultContext(VariableScope.VARIABLE_SCOPE)
+                : null;
+    }
+
+    /**
+     * @param runtime runtime used to fire variable changed events; when 
{@code null} no events are fired
+     */
+    static void migrate(KogitoProcessRuntime runtime, RuleFlowProcessInstance 
processInstance, List<VariableMigrationPlan> plans) {
+        if (plans.isEmpty()) {
+            return;
+        }
+        VariableScopeInstance variables = (VariableScopeInstance) 
processInstance.getContextInstance(VariableScope.VARIABLE_SCOPE);
+        if (variables == null) {
+            LOGGER.warn("Process instance {} has no variable scope, {} 
variable migration rule(s) not applied", processInstance.getStringId(), 
plans.size());
+            return;
+        }
+        VariableMigrator migrator = new VariableMigrator(runtime, 
processInstance, variables);
+        plans.forEach(migrator::apply);
+    }
+
+    private void apply(VariableMigrationPlan plan) {
+        LOGGER.debug("Applying {} to process instance {}", plan, 
processInstance.getStringId());
+        switch (plan.getAction()) {
+            case RENAME:
+                rename(plan.getFrom(), plan.getTo());
+                break;
+            case DEFAULT:
+                applyDefault(plan.getName(), plan.getValue());
+                break;
+            case REMOVE:
+                change(plan.getName(), null);
+                break;
+        }
+    }
+
+    /**
+     * Moves the value of {@code from} to {@code to}. An existing value in 
{@code to} is overwritten.
+     */
+    private void rename(String from, String to) {
+        Object value = valueOf(from);
+        if (value == null || from.equals(to)) {
+            return;
+        }
+        if (valueOf(to) != null) {
+            LOGGER.warn("Process instance {}: renaming variable '{}' 
overwrites the existing value of variable '{}'", processInstance.getStringId(), 
from, to);
+        }
+        verifyTargetType(to, value);
+        change(to, value);
+        change(from, null);
+    }
+
+    private void applyDefault(String name, Object value) {
+        if (valueOf(name) == null) {
+            verifyTargetType(name, value);
+            change(name, value);
+        }
+    }
+
+    private void change(String name, Object newValue) {
+        Object oldValue = valueOf(name);
+        if (Objects.equals(oldValue, newValue)) {
+            return;
+        }
+        List<String> tags = targetDefinition != null ? 
targetDefinition.tags(name) : Collections.emptyList();
+        if (runtime != null) {
+            runtime.getProcessEventSupport().fireBeforeVariableChanged(name, 
name, oldValue, newValue, tags, processInstance, null, runtime.getKieRuntime());
+        }
+        variables.internalSetVariable(name, newValue);
+        if (runtime != null) {
+            runtime.getProcessEventSupport().fireAfterVariableChanged(name, 
name, oldValue, newValue, tags, processInstance, null, runtime.getKieRuntime());
+        }
+    }
+
+    private Object valueOf(String name) {
+        return variables.getVariables().get(name);
+    }
+
+    /**
+     * Fails the migration when the value does not match the type declared for 
the variable in the target process.
+     * Variables not declared in the target process are not checked.
+     */
+    private void verifyTargetType(String name, Object value) {
+        Variable variable = targetDefinition != null ? 
targetDefinition.findVariable(name) : null;
+        if (value != null && variable != null && variable.getType() != null && 
!variable.getType().verifyDataType(value)) {
+            throw new IllegalArgumentException(String.format(
+                    "Cannot migrate process instance %s: variable '%s' in 
target process %s expects type %s but the value is of type %s",
+                    processInstance.getStringId(), name, 
processInstance.getProcessId(), variable.getType().getStringType(), 
value.getClass().getName()));
+        }
+    }
+}
diff --git 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/impl/JsonMigrationPlanFileReader.java
 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/impl/JsonMigrationPlanFileReader.java
index a37c00a5147..6c624ce4938 100644
--- 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/impl/JsonMigrationPlanFileReader.java
+++ 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/impl/JsonMigrationPlanFileReader.java
@@ -24,6 +24,7 @@ import java.io.InputStream;
 import org.jbpm.flow.migration.MigrationPlanFileFormatException;
 import org.jbpm.flow.migration.MigrationPlanFileReader;
 import org.jbpm.flow.migration.model.MigrationPlan;
+import org.jbpm.flow.migration.model.VariableMigrationPlan;
 import org.kie.api.definition.process.WorkflowElementIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -49,9 +50,14 @@ public class JsonMigrationPlanFileReader implements 
MigrationPlanFileReader {
 
             MigrationPlan migrationPlan = objectMapper.readValue(is, 
MigrationPlan.class);
             LOGGER.trace("Read migration plan {} in json format", 
migrationPlan);
+            if (migrationPlan.getProcessMigrationPlan() != null) {
+                
migrationPlan.getProcessMigrationPlan().getVariableMigrationPlan().forEach(VariableMigrationPlan::validate);
+            }
             return migrationPlan;
         } catch (IOException e) {
             throw new MigrationPlanFileFormatException("Error during 
marshalling", e);
+        } catch (IllegalArgumentException e) {
+            throw new MigrationPlanFileFormatException("Invalid variable 
migration plan: " + e.getMessage(), e);
         }
     }
 
diff --git 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/model/ProcessInstanceMigrationPlan.java
 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/model/ProcessInstanceMigrationPlan.java
index 3a49d218627..371715c2cc5 100644
--- 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/model/ProcessInstanceMigrationPlan.java
+++ 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/model/ProcessInstanceMigrationPlan.java
@@ -18,6 +18,7 @@
  */
 package org.jbpm.flow.migration.model;
 
+import java.util.Collections;
 import java.util.List;
 import java.util.Objects;
 
@@ -31,6 +32,16 @@ public class ProcessInstanceMigrationPlan {
 
     private List<NodeInstanceMigrationPlan> nodeInstanceMigrationPlan;
 
+    private List<VariableMigrationPlan> variableMigrationPlan;
+
+    public List<VariableMigrationPlan> getVariableMigrationPlan() {
+        return variableMigrationPlan != null ? variableMigrationPlan : 
Collections.emptyList();
+    }
+
+    public void setVariableMigrationPlan(List<VariableMigrationPlan> 
variableMigrationPlan) {
+        this.variableMigrationPlan = variableMigrationPlan;
+    }
+
     public List<NodeInstanceMigrationPlan> getNodeInstanceMigrationPlan() {
         return nodeInstanceMigrationPlan;
     }
@@ -72,7 +83,7 @@ public class ProcessInstanceMigrationPlan {
 
     @Override
     public int hashCode() {
-        return Objects.hash(nodeInstanceMigrationPlan, 
sourceProcessDefinition, targetProcessDefinition);
+        return Objects.hash(nodeInstanceMigrationPlan, variableMigrationPlan, 
sourceProcessDefinition, targetProcessDefinition);
     }
 
     @Override
@@ -84,7 +95,8 @@ public class ProcessInstanceMigrationPlan {
         if (getClass() != obj.getClass())
             return false;
         ProcessInstanceMigrationPlan other = (ProcessInstanceMigrationPlan) 
obj;
-        return Objects.equals(nodeInstanceMigrationPlan, 
other.nodeInstanceMigrationPlan) && Objects.equals(sourceProcessDefinition, 
other.sourceProcessDefinition)
+        return Objects.equals(nodeInstanceMigrationPlan, 
other.nodeInstanceMigrationPlan) && Objects.equals(variableMigrationPlan, 
other.variableMigrationPlan)
+                && Objects.equals(sourceProcessDefinition, 
other.sourceProcessDefinition)
                 && Objects.equals(targetProcessDefinition, 
other.targetProcessDefinition);
     }
 
diff --git 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/MigrationPlanFileFormatException.java
 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/model/VariableMigrationAction.java
similarity index 55%
copy from 
kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/MigrationPlanFileFormatException.java
copy to 
kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/model/VariableMigrationAction.java
index a410f821b05..c03ed557d21 100644
--- 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/MigrationPlanFileFormatException.java
+++ 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/model/VariableMigrationAction.java
@@ -16,20 +16,31 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-package org.jbpm.flow.migration;
+package org.jbpm.flow.migration.model;
 
-import java.io.IOException;
+import com.fasterxml.jackson.annotation.JsonProperty;
 
-public class MigrationPlanFileFormatException extends IOException {
-
-    private static final long serialVersionUID = 1L;
+/**
+ * Actions a variable migration rule can perform on a process instance being 
migrated.
+ */
+public enum VariableMigrationAction {
 
-    public MigrationPlanFileFormatException(String msg) {
-        super(msg);
-    }
+    /**
+     * Copies the value of {@code from} into {@code to} and clears {@code 
from}.
+     * Does nothing when {@code from} has no value.
+     */
+    @JsonProperty("rename")
+    RENAME,
 
-    public MigrationPlanFileFormatException(String msg, IOException e) {
-        super(msg, e);
-    }
+    /**
+     * Sets {@code name} to {@code value} only when the variable has no value.
+     */
+    @JsonProperty("default")
+    DEFAULT,
 
+    /**
+     * Clears {@code name} (sets it to {@code null}).
+     */
+    @JsonProperty("remove")
+    REMOVE
 }
diff --git 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/model/VariableMigrationPlan.java
 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/model/VariableMigrationPlan.java
new file mode 100644
index 00000000000..e91830b6779
--- /dev/null
+++ 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/migration/model/VariableMigrationPlan.java
@@ -0,0 +1,154 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.jbpm.flow.migration.model;
+
+import java.util.Objects;
+
+/**
+ * A rule that changes a process instance variable while the instance is 
migrated.
+ * Which fields are used depends on the {@link VariableMigrationAction}:
+ * <ul>
+ * <li>{@code rename}: {@code from} and {@code to}. An existing value in 
{@code to} is overwritten (a warning is logged).</li>
+ * <li>{@code default}: {@code name} and {@code value}. Only applied when the 
variable has no value.</li>
+ * <li>{@code remove}: {@code name}</li>
+ * </ul>
+ * {@code rename} and {@code remove} set the old variable to {@code null}; the 
variable name itself stays in the
+ * process instance variables. Values written to a variable declared in the 
target process must match its type,
+ * otherwise the migration fails.
+ */
+public class VariableMigrationPlan {
+
+    private VariableMigrationAction action;
+    private String name;
+    private String from;
+    private String to;
+    private Object value;
+
+    public VariableMigrationPlan() {
+        // do nothing
+    }
+
+    public VariableMigrationPlan(VariableMigrationAction action, String name, 
String from, String to, Object value) {
+        this.action = action;
+        this.name = name;
+        this.from = from;
+        this.to = to;
+        this.value = value;
+    }
+
+    public VariableMigrationAction getAction() {
+        return action;
+    }
+
+    public void setAction(VariableMigrationAction action) {
+        this.action = action;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getFrom() {
+        return from;
+    }
+
+    public void setFrom(String from) {
+        this.from = from;
+    }
+
+    public String getTo() {
+        return to;
+    }
+
+    public void setTo(String to) {
+        this.to = to;
+    }
+
+    public Object getValue() {
+        return value;
+    }
+
+    public void setValue(Object value) {
+        this.value = value;
+    }
+
+    /**
+     * Checks that the fields required by the action are present.
+     *
+     * @throws IllegalArgumentException if the action or one of its required 
fields is missing,
+     *         or if a rename has the same {@code from} and {@code to}
+     */
+    public void validate() {
+        if (action == null) {
+            throw new IllegalArgumentException("Variable migration plan 
without action: " + this);
+        }
+        switch (action) {
+            case RENAME:
+                requireField("from", from);
+                requireField("to", to);
+                if (from.equals(to)) {
+                    throw new IllegalArgumentException("Variable migration 
plan " + this + " renames a variable to itself");
+                }
+                break;
+            case DEFAULT:
+                requireField("name", name);
+                if (value == null) {
+                    throw new IllegalArgumentException("Variable migration 
plan " + this + " requires field value");
+                }
+                break;
+            case REMOVE:
+                requireField("name", name);
+                break;
+        }
+    }
+
+    private void requireField(String field, String fieldValue) {
+        if (fieldValue == null || fieldValue.isBlank()) {
+            throw new IllegalArgumentException("Variable migration plan " + 
this + " requires field " + field);
+        }
+    }
+
+    @Override
+    public String toString() {
+        return "VariableMigrationPlan [action=" + action + ", name=" + name + 
", from=" + from + ", to=" + to + ", value=" + value + "]";
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(action, name, from, to, value);
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj)
+            return true;
+        if (obj == null)
+            return false;
+        if (getClass() != obj.getClass())
+            return false;
+        VariableMigrationPlan other = (VariableMigrationPlan) obj;
+        return action == other.action && Objects.equals(name, other.name) && 
Objects.equals(from, other.from) && Objects.equals(to, other.to)
+                && Objects.equals(value, other.value);
+    }
+
+}
diff --git 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/serialization/migration/StandardMigrationProcessInstanceMarshallerListener.java
 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/serialization/migration/StandardMigrationProcessInstanceMarshallerListener.java
index b938110a994..e9dd8bb76c2 100644
--- 
a/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/serialization/migration/StandardMigrationProcessInstanceMarshallerListener.java
+++ 
b/kogito-jbpm/jbpm-flow-migration/src/main/java/org/jbpm/flow/serialization/migration/StandardMigrationProcessInstanceMarshallerListener.java
@@ -53,7 +53,7 @@ public class 
StandardMigrationProcessInstanceMarshallerListener implements Proce
         }
         LOGGER.debug("Migration processInstance state {}-{} and definition 
{}-{}",
                 processInstance.getProcessId(), 
processInstance.getProcessVersion(), processInstance.getProcess().getId(), 
processInstance.getProcess().getVersion());
-        
migrationPlanService.migrateProcessElement(runtime.getApplication().get(Processes.class),
 processInstance);
+        migrationPlanService.migrateProcessElement(runtime, 
runtime.getApplication().get(Processes.class), processInstance);
         runtime.getProcessEventSupport().fireOnMigration(processInstance, 
runtime.getKieRuntime());
 
     }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to