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

heneveld pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/brooklyn-server.git


The following commit(s) were added to refs/heads/master by this push:
     new 23be310631 Implements list index specifiers for workflows
     new 8d87863b64 Merge pull request #1398 from nakomis/index-specifiers
23be310631 is described below

commit 23be310631217ddb43a1bb8deca6f7319bb2f516
Author: Martin Harris <[email protected]>
AuthorDate: Wed May 10 14:50:09 2023 +0100

    Implements list index specifiers for workflows
---
 .../steps/variables/SetVariableWorkflowStep.java   |  28 ++++-
 .../core/workflow/WorkflowMapAndListTest.java      | 120 +++++++++++++++++++++
 .../core/workflow/WorkflowTransformTest.java       |  24 +++++
 3 files changed, 167 insertions(+), 5 deletions(-)

diff --git 
a/core/src/main/java/org/apache/brooklyn/core/workflow/steps/variables/SetVariableWorkflowStep.java
 
b/core/src/main/java/org/apache/brooklyn/core/workflow/steps/variables/SetVariableWorkflowStep.java
index 15b10528ae..9f76bd1da5 100644
--- 
a/core/src/main/java/org/apache/brooklyn/core/workflow/steps/variables/SetVariableWorkflowStep.java
+++ 
b/core/src/main/java/org/apache/brooklyn/core/workflow/steps/variables/SetVariableWorkflowStep.java
@@ -112,15 +112,33 @@ public class SetVariableWorkflowStep extends 
WorkflowStepDefinition {
             if ("output".equals(names0)) throw new 
IllegalArgumentException("Cannot set subfield in output");  // catch common 
error
             Object h = 
context.getWorkflowExectionContext().getWorkflowScratchVariables().get(names0);
             if (!(h instanceof Map)) throw new 
IllegalArgumentException("Cannot set " + name + " because " + names0 + " is " + 
(h == null ? "unset" : "not a map"));
-            for (int i=1; i<names.length-1; i++) {
+            for (int i = 1; i < names.length - 1; i++) {
                 Object hi = ((Map<?, ?>) h).get(names[i]);
-                if (hi==null) {
+                if (hi == null) {
                     hi = MutableMap.of();
-                    ((Map)h).put(names[i], hi);
-                } else if (!(hi instanceof Map)) throw new 
IllegalArgumentException("Cannot set " + name + " because " + names[i] + " is 
not a map");
+                    ((Map) h).put(names[i], hi);
+                } else if (!(hi instanceof Map))
+                    throw new IllegalArgumentException("Cannot set " + name + 
" because " + names[i] + " is not a map");
                 h = hi;
             }
-            oldValue = ((Map)h).put(names[names.length-1], resolvedValue);
+            oldValue = ((Map) h).put(names[names.length - 1], resolvedValue);
+        } else if (name.contains("[")) {
+            String[] names = name.split("((?<=\\[|\\])|(?=\\[|\\]))");
+            if (names.length != 4 || !"[".equals(names[1]) || 
!"]".equals(names[3])) {
+                throw new IllegalArgumentException("Invalid list index 
specifier " + name);
+            }
+            String listName = names[0];
+            int listIndex = Integer.parseInt(names[2]);
+            Object o = 
context.getWorkflowExectionContext().getWorkflowScratchVariables().get(listName);
+            if (!(o instanceof List))
+                throw new IllegalArgumentException("Cannot set " + name + " 
because " + listName + " is " + (o == null ? "unset" : "not a list"));
+
+            List l = MutableList.copyOf(((List)o));
+            if (listIndex < 0 || listIndex >= l.size()) {
+                throw new IllegalArgumentException("Invalid list index " + 
listIndex);
+            }
+            oldValue = l.set(listIndex, resolvedValue);
+            
context.getWorkflowExectionContext().getWorkflowScratchVariables().put(listName,
 l);
         } else {
             oldValue = 
context.getWorkflowExectionContext().getWorkflowScratchVariables().put(name, 
resolvedValue);
         }
diff --git 
a/core/src/test/java/org/apache/brooklyn/core/workflow/WorkflowMapAndListTest.java
 
b/core/src/test/java/org/apache/brooklyn/core/workflow/WorkflowMapAndListTest.java
new file mode 100644
index 0000000000..ea5d82bd56
--- /dev/null
+++ 
b/core/src/test/java/org/apache/brooklyn/core/workflow/WorkflowMapAndListTest.java
@@ -0,0 +1,120 @@
+/*
+ * 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.apache.brooklyn.core.workflow;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import org.apache.brooklyn.api.entity.EntityLocal;
+import org.apache.brooklyn.api.entity.EntitySpec;
+import org.apache.brooklyn.core.test.BrooklynMgmtUnitTestSupport;
+import org.apache.brooklyn.entity.stock.BasicApplication;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.core.config.ConfigBag;
+import org.apache.brooklyn.util.exceptions.PropagatedRuntimeException;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import java.util.List;
+
+public class WorkflowMapAndListTest  extends BrooklynMgmtUnitTestSupport {
+
+    private BasicApplication app;
+
+    Object runSteps(List<?> steps) {
+        WorkflowBasicTest.addWorkflowStepTypes(mgmt);
+
+        BasicApplication app = 
mgmt().getEntityManager().createEntity(EntitySpec.create(BasicApplication.class));
+        this.app = app;
+        WorkflowEffector eff = new WorkflowEffector(ConfigBag.newInstance()
+                .configure(WorkflowEffector.EFFECTOR_NAME, "myWorkflow")
+                .configure(WorkflowEffector.STEPS, (List) steps)
+        );
+        eff.apply((EntityLocal)app);
+        return 
app.invoke(app.getEntityType().getEffectorByName("myWorkflow").get(), 
null).getUnchecked();
+    }
+
+    @Test
+    public void testMapDirect() {
+        Object result = runSteps(MutableList.of(
+                "let map myMap = {}",
+                "let myMap.a = 1",
+                "return ${myMap.a}"
+        ));
+        Asserts.assertEquals(result, "1");
+    }
+
+    @Test
+    public void testSetSensorMap() {
+        Object result = runSteps(MutableList.of(
+                "set-sensor service.problems[latency] = \"too slow\"",
+                "let x = ${entity.sensor['service.problems']}",
+                "return ${x}"
+        ));
+        Asserts.assertEquals(result, ImmutableMap.of("latency", "too slow"));
+    }
+
+    @Test
+    public void testListIndex() {
+        Object result = runSteps(MutableList.of(
+                "let list mylist = [1, 2, 3]",
+                "let mylist[1] = 4",
+                "return ${mylist[1]}"
+        ));
+        Asserts.assertEquals(result, "4");
+    }
+
+    @Test
+    public void testUndefinedList() {
+        Object result = null;
+        try {
+            result = runSteps(MutableList.of(
+                    "let list mylist = [1, 2, 3]",
+                    "let anotherList[1] = 4",
+                    "return ${anotherList[1]}"
+            ));
+        } catch (Exception e) {
+            // We can't use expectedExceptionsMessageRegExp as the error 
message is in the `Cause` exception
+            if (e.getCause() == null || 
!e.getCause().getMessage().contains("Cannot set anotherList[1] because 
anotherList is unset")) {
+                Assert.fail("Expected cause exception to contain 'Cannot set 
anotherList[1] because anotherList is unset'");
+            }
+            return;
+        }
+        Assert.fail("Expected IllegalArgumentException");
+    }
+
+    @Test
+    public void testInvalidListSpecifier() {
+        Object result = null;
+        try {
+            result = runSteps(MutableList.of(
+                    "let list mylist = [1, 2, 3]",
+                    "let mylist[1 = 4",
+                    "return ${mylist[1]}"
+            ));
+        } catch (Exception e) {
+            // We can't use expectedExceptionsMessageRegExp as the error 
message is in the `Cause` exception
+            if (e.getCause() == null || 
!e.getCause().getMessage().contains("Invalid list index specifier mylist[1")) {
+                Assert.fail("Expected cause exception to contain 'Invalid list 
index specifier mylist[1'");
+            }
+            return;
+        }
+        Assert.fail("Expected IllegalArgumentException");
+    }
+}
diff --git 
a/core/src/test/java/org/apache/brooklyn/core/workflow/WorkflowTransformTest.java
 
b/core/src/test/java/org/apache/brooklyn/core/workflow/WorkflowTransformTest.java
index 0e66f257a5..27cb2642a8 100644
--- 
a/core/src/test/java/org/apache/brooklyn/core/workflow/WorkflowTransformTest.java
+++ 
b/core/src/test/java/org/apache/brooklyn/core/workflow/WorkflowTransformTest.java
@@ -199,4 +199,28 @@ public class WorkflowTransformTest extends 
BrooklynMgmtUnitTestSupport {
         Asserts.assertEquals(result, "abXXXf ghi");
     }
 
+    @Test
+    public void testMapDirect() {
+
+        loadTypes();
+
+        BasicApplication app = 
mgmt.getEntityManager().createEntity(EntitySpec.create(BasicApplication.class));
+
+        WorkflowEffector eff = new WorkflowEffector(ConfigBag.newInstance()
+                .configure(WorkflowEffector.EFFECTOR_NAME, "myWorkflow")
+                .configure(WorkflowEffector.EFFECTOR_PARAMETER_DEFS, 
MutableMap.of("p1", MutableMap.of("defaultValue", "p1v")))
+                .configure(WorkflowEffector.STEPS, MutableList.<Object>of()
+                        .append("let map myMap = {a: 1}")
+                        .append("let myMap.a = 2")
+                        .append("return ${myMap.a}")
+                )
+        );
+        eff.apply((EntityLocal)app);
+
+        Task<?> invocation = 
app.invoke(app.getEntityType().getEffectorByName("myWorkflow").get(), null);
+        Object result = invocation.getUnchecked();
+        Asserts.assertNotNull(result);
+        Asserts.assertEquals(result, "2");
+    }
+
 }

Reply via email to