Search code examples
javascriptcamundascript-task

Debugging a Javascript within Camunda's Script-Task


I'm trying to merge two arrays in a Script Task of type Javascript within a Process in Camunda. Here's my script:

var arr1 = execution.getVariableTyped("arr1", true);
var arr2 = execution.getVariableTyped("arr2", true);

var merged = [];

for (var i1 in arr1) {
    var found = false;
    for (var i2 in merged) {
        if (arr1[i1].id == merged[i2].id) {
            found = true;
            break;
        }
    }
    if (!found) {
        merged.push(arr1[i1]);
    }
}

for (var i1 in arr2) {
    var found = false;
    for (var i2 in merged) {
        if (arr2[i1].id == merged[i2].id) {
            found = true;
            break;
        }
    }
    if (!found) {
        merged.push(arr2[i1]);
    }
}

execution.setVariable("arr1", merged);
execution.removeVariable("arr2");

When the mentioned script is executed, it throws an exception:

Cannot complete task b4fb856a-6a92-11e5-9774-005056c00008: Cannot serialize object in variable 'arr1': SPIN/JACKSON-JSON-01009 Unable to map object 'jdk.nashorn.internal.objects.NativeArray@5ff42b74' to json node

Why is that? What's the problem and how can I fix it? Is there anyway to debug such scripts?


Solution

  • Nashorn has classes like NativeArray for Javascript arrays because a Javascript array is not tied to an element type like for example String[] in Java. Thus, Nashorn creates an instance of NativeArray. Apparently, the process engine is not able to store instances of NativeArray since it does not implement java.io.Serializable and is not serializable by the JSON and XML serializer either. In fact, the JSON serializer attempts to do so but throws the exception you see.

    You can do

    execution.setVariable("arr1", Java.to(merged, "java.lang.Object[]"));
    

    to convert the NativeArray to a Java Object[]. If you want to access the array from Java code, you could use a more specifically typed array. Source: Nashorn documentation

    Note:

    For JDK 8 versions >= 1.8u40, the type handed over is not NativeArray but an instance of ScriptObjectMirror that wraps a NativeArray (see this question for details). Apparently, the same code can be used to solve the issue.