Make default value type object 57/32657/4
authorsubhash kumar singh <subhash.kumar.singh@huawei.com>
Fri, 23 Feb 2018 06:05:28 +0000 (06:05 +0000)
committersubhash kumar singh <subhash.kumar.singh@huawei.com>
Wed, 28 Feb 2018 09:12:38 +0000 (09:12 +0000)
Enhance default value type from String to Object so that it will
directly support different type (BOOL, Array, Map).

Issue-ID: CLI-74
Change-Id: Iaca438e58150c80047340acba92917ecae685242
Signed-off-by: subhash kumar singh <subhash.kumar.singh@huawei.com>
framework/src/main/java/org/onap/cli/fw/input/OnapCommandParameter.java
framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaLoader.java
framework/src/main/java/org/onap/cli/fw/utils/OnapCommandHelperUtils.java
framework/src/test/java/org/onap/cli/fw/input/OnapCommandParameterTest.java
framework/src/test/java/org/onap/cli/fw/utils/OnapCommandUtilsTest.java
framework/src/test/resources/open-cli-schema/sample-test-schema.yaml
main/src/main/java/org/onap/cli/main/utils/OnapCliArgsParser.java
main/src/test/java/org/onap/cli/main/utils/OnapCliUtilsTest.java
profiles/http/src/main/java/org/onap/cli/fw/http/cmd/OnapHttpCommand.java

index 465dffa..22f341d 100644 (file)
 
 package org.onap.cli.fw.input;
 
-import java.io.File;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
+import com.fasterxml.jackson.databind.ObjectMapper;
 import org.onap.cli.fw.error.OnapCommandException;
 import org.onap.cli.fw.error.OnapCommandInvalidParameterValue;
 import org.onap.cli.fw.error.OnapCommandParameterMissing;
 import org.onap.cli.fw.utils.OnapCommandUtils;
 
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
 
 /**
  * Oclip Command's input parameter.
@@ -63,7 +65,7 @@ public class OnapCommandParameter {
     /*
      * Default value
      */
-    private String defaultValue = "";
+    private Object defaultValue;
 
     /*
      * raw default value, stored with out processing it.
@@ -150,12 +152,24 @@ public class OnapCommandParameter {
     public void setParameterType(OnapCommandParameterType parameterType) {
         this.parameterType = parameterType;
 
-        if (this.defaultValue.isEmpty()) {
-            if (this.getParameterType().equals(OnapCommandParameterType.BOOL)) {
-                // For bool type always the default param is false
-                this.defaultValue = "false";
-            } else if (this.getParameterType().equals(OnapCommandParameterType.UUID)) {
-                this.defaultValue = UUID.randomUUID().toString();
+        if (defaultValue == null) {
+
+            switch (getParameterType()) {
+                case MAP:
+                    this.defaultValue = new HashMap<String, String>();
+                    break;
+                case ARRAY:
+                    defaultValue = new ArrayList<String>();
+                    break;
+                case BOOL:
+                    defaultValue = false;
+                    break;
+                case UUID:
+                    this.defaultValue = UUID.randomUUID().toString();
+                    break;
+                default:
+                    this.defaultValue = null;
+                    break;
             }
         }
     }
@@ -165,7 +179,7 @@ public class OnapCommandParameter {
      *
      * @return string
      */
-    public String getDefaultValue() {
+    public Object getDefaultValue() {
         return defaultValue;
     }
 
@@ -187,9 +201,63 @@ public class OnapCommandParameter {
         return this.rawDefaultValue.trim().substring(7, this.rawDefaultValue.length() - 1);
     }
 
-    public void setDefaultValue(String defaultValue) {
-        this.rawDefaultValue = defaultValue;
-        this.defaultValue = OnapCommandUtils.replaceLineForSpecialValues(this.rawDefaultValue);
+    public void setRawDefaultValue(String value) throws OnapCommandInvalidParameterValue {
+        this.rawDefaultValue = value;
+        String processedValue= OnapCommandUtils.replaceLineForSpecialValues(value);
+
+        switch (parameterType) {
+            case MAP:
+                try {
+                    defaultValue = new ObjectMapper().readValue(processedValue, Map.class);
+                } catch (IOException e) {
+                    throw new OnapCommandInvalidParameterValue("Invalid default value for " + this.getName(), e);
+                }
+                break;
+
+            case ARRAY:
+                try {
+                    defaultValue = new ObjectMapper().readValue(processedValue, List.class);
+                } catch (IOException e) {
+                    throw new OnapCommandInvalidParameterValue("Invalid default value for " + this.getName(), e);
+                }
+                break;
+
+            case BOOL:
+                defaultValue = processedValue.equalsIgnoreCase("true");
+                break;
+
+            default:
+                defaultValue = processedValue;
+                break;
+        }
+    }
+
+    public void setDefaultValue(Object defaultValue) throws OnapCommandInvalidParameterValue {
+        //check type
+        Class<?> clz;
+        switch (parameterType) {
+            case BOOL:
+                clz = Boolean.class;
+                break;
+
+            case MAP:
+                clz = Map.class;
+                break;
+
+            case ARRAY:
+                clz = Collection.class;
+                break;
+
+            default:
+                clz = String.class;
+                break;
+        }
+
+        if (clz.isInstance(defaultValue)) {
+            this.defaultValue = defaultValue;
+        } else {
+            throw new OnapCommandInvalidParameterValue("Invalid default value for parameter: " + this.getName());
+        }
     }
 
     /**
@@ -212,34 +280,22 @@ public class OnapCommandParameter {
 
         if (OnapCommandParameterType.URL.equals(parameterType) && !value.toString().isEmpty() && !value.toString().startsWith("http")
                 && !value.toString().startsWith("/")) {
-            this.value = "/" + value;
+            value = "/" + value;
         } else if (OnapCommandParameterType.ARRAY.equals(parameterType)) {
             if (!(value instanceof List)) {
                 throw new OnapCommandInvalidParameterValue(this.getName());
             }
 
-            List<String> list = (List<String>) value;
-            ObjectMapper mapper = new ObjectMapper();
-            try {
-                this.value = mapper.writeValueAsString(list);
-            } catch (JsonProcessingException e) {
-                throw new OnapCommandInvalidParameterValue(this.getName(), e);
-            }
         } else if (OnapCommandParameterType.MAP.equals(parameterType)) {
             if (!(value instanceof Map)) {
                 throw new OnapCommandInvalidParameterValue(this.getName());
             }
-
-            Map<String, String> map = (Map<String, String>) value;
-            ObjectMapper mapper = new ObjectMapper();
-            try {
-                this.value = mapper.writeValueAsString(map);
-            } catch (JsonProcessingException e) {
-                throw new OnapCommandInvalidParameterValue(this.getName(), e);
+        } else if (OnapCommandParameterType.BOOL.equals(parameterType)) {
+            if (!(value instanceof Boolean)) {
+                throw new OnapCommandInvalidParameterValue(this.getName());
             }
-        } else {
-            this.value = value;
         }
+        this.value = value;
     }
 
     public boolean isOptional() {
index b47000a..439eb97 100644 (file)
@@ -318,7 +318,7 @@ public class OnapCommandSchemaLoader {
 
                                     case DEFAULT_VALUE:
                                         Object obj = parameter.get(key2);
-                                        param.setDefaultValue(obj.toString());
+                                        param.setRawDefaultValue(obj.toString());
                                         break;
 
                                     case TYPE:
index e9ea81d..1387ea3 100644 (file)
@@ -157,7 +157,7 @@ public class OnapCommandHelperUtils {
             if (param.isRawDefaultValueAnEnv()) {
                 optSecondCol += defaultMsg + "read from environment variable " + param.getEnvVarNameFromrRawDefaultValue()
                         + ".";
-            } else if (param.getDefaultValue() != null && !((String)param.getDefaultValue()).isEmpty()) {
+            } else if (param.getDefaultValue() != null && param.getDefaultValue().toString().isEmpty()) {
                 optSecondCol += defaultMsg + param.getDefaultValue() + ".";
             }
 
index 82781b4..5a6e645 100644 (file)
@@ -20,6 +20,7 @@ import static org.junit.Assert.assertTrue;
 
 import java.util.Arrays;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 import org.junit.Test;
@@ -49,8 +50,13 @@ public class OnapCommandParameterTest {
         assertTrue("value".equals(param.getValue()));
 
         param.setParameterType(OnapCommandParameterType.ARRAY);
-        param.setValue(Arrays.asList("1", "2", "3"));
-        assertTrue("[\"1\",\"2\",\"3\"]".equals(param.getValue()));
+        List<String> list = Arrays.asList("1", "2", "3");
+        param.setValue(list);
+        assertTrue(((List)param.getValue()).containsAll(list));
+
+        param.setRawDefaultValue("[\"1\", \"2\", \"3\", \"4\"]");
+        assertTrue(((List<String>)param.getDefaultValue())
+                .containsAll(Arrays.asList("1", "2", "3", "4")));
 
         param.setParameterType(OnapCommandParameterType.MAP);
         Map<String, String> map = new HashMap<>();
@@ -58,16 +64,20 @@ public class OnapCommandParameterTest {
         map.put("Two", "2");
         map.put("Three", "3");
         param.setValue(map);
-        assertTrue("{\"One\":\"1\",\"Two\":\"2\",\"Three\":\"3\"}".equals(param.getValue()));
-
-        param.setDefaultValue("$s{env:defaultValue}");
-        assertTrue("env:defaultValue".equals(param.getDefaultValue()));
+        HashMap<String, String> value = (HashMap<String, String>) param.getValue();
+        assertTrue(value.keySet().containsAll(Arrays.asList("One", "Two", "Three")));
+        assertTrue(value.values().containsAll(Arrays.asList("1", "2", "3")));
+
+        param.setRawDefaultValue("{\"key1\":\"$s{env:defaultValue}\"}");
+        assertTrue(((Map<String, String>)param.getDefaultValue()).values().containsAll(
+                Arrays.asList("env:defaultValue")
+        ));
     }
 
     @Test
-    public void parameterEnvDefaultValueObjTest() {
+    public void parameterEnvDefaultValueObjTest() throws OnapCommandInvalidParameterValue {
         OnapCommandParameter param = new OnapCommandParameter();
-        param.setDefaultValue("$s{env:DAFAULT_VALUE}");
+        param.setRawDefaultValue("$s{env:DAFAULT_VALUE}");
         boolean isDefaultValueAnEnv = param.isRawDefaultValueAnEnv();
         assertTrue(isDefaultValueAnEnv);
 
index 317920f..11f9707 100644 (file)
 package org.onap.cli.fw.utils;
 
 
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
+import mockit.Invocation;
+import mockit.Mock;
+import mockit.MockUp;
 import org.junit.FixMethodOrder;
 import org.junit.Ignore;
 import org.junit.Test;
@@ -48,9 +39,18 @@ import org.onap.cli.fw.schema.OnapCommandSchema;
 import org.onap.cli.fw.schema.OnapCommandSchemaInfo;
 import org.onap.cli.fw.schema.OnapCommandSchemaLoader;
 
-import mockit.Invocation;
-import mockit.Mock;
-import mockit.MockUp;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 
 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
 public class OnapCommandUtilsTest {
@@ -119,7 +119,7 @@ public class OnapCommandUtilsTest {
     public void loadOnapCommandSchemaWithOutDefaultTest() throws OnapCommandException {
         OnapCommand cmd = new OnapCommandSample();
         OnapCommandSchemaLoader.loadSchema(cmd, "sample-test-schema.yaml", false, false);
-        assertTrue("sample-test".equals(cmd.getName()) && cmd.getParameters().size() == 9);
+        assertTrue("sample-test".equals(cmd.getName()) && cmd.getParameters().size() == 10);
     }
 
     @Test(expected = OnapCommandParameterNameConflict.class)
@@ -147,14 +147,44 @@ public class OnapCommandUtilsTest {
         assertTrue("sample-test".equals(cmd.getName()) && cmd.getParameters().size() > 9);
 
         for (OnapCommandParameter com : cmd.getParameters()) {
-            com.setValue("value");
+            switch (com.getParameterType()) {
+                case STRING:
+                    com.setValue("value");
+                    break;
+
+                case ARRAY:
+                    com.setValue(Collections.EMPTY_LIST);
+                    break;
+
+                case MAP:
+                    com.setValue(new HashMap<String, String>());
+                    break;
+
+                case BOOL:
+                    com.setValue(true);
+                    break;
+
+                case TEXT:
+                    com.setValue("value");
+                    break;
+
+                case URL:
+                    com.setValue("http:localhost/test");
+                    break;
+
+                case JSON:
+                    com.setValue("json");
+                    break;
+
+                default:
+                    break;
+            }
         }
 
         Map<String, OnapCommandParameter> map = OnapCommandUtils.getInputMap(cmd.getParameters());
-        assertTrue(map.size() == 15);
+        assertTrue(map.size() == 16);
     }
 
-
     @Test
     public void helpCommandTest() throws IOException, OnapCommandException {
         OnapCommand cmd = new OnapCommandSample();
index 3c4ace8..f4894b3 100644 (file)
@@ -69,6 +69,12 @@ parameters:
     description: Oclip positional args, if no short option and no long option given for it
     is_optional: true
     default_value: http://localhost:8082/file.txt
+  - name: array-param
+    type: array
+    description: list parameter
+    long_option: list-param
+    short_option: q
+    is_optional: true
 results:
   direction: portrait
   attributes:
index fdf6d5b..16d6a28 100644 (file)
@@ -105,7 +105,7 @@ public class OnapCliArgsParser {
                 // end of the list or if its option rather than a value
                 if ((i + 1) == args.size() || args.get(i + 1).startsWith("-")) {
                     if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.BOOL)) {
-                        paramMap.get(paramName).setValue("true");
+                        paramMap.get(paramName).setValue(true);
                         continue;
                     }
                     throw new OnapCliArgumentValueMissing(args.get(i));
@@ -124,13 +124,8 @@ public class OnapCliArgsParser {
                 } else if (paramMap.get(paramName).getParameterType()
                         .equals(OnapCommandParameterType.ARRAY)) {
                     Object value = paramMap.get(paramName).getValue();
-                    List<String> list;
-                    if (value == "") {
-                        list = new ArrayList<>();
-                    } else {
-                        list = convertJsonToListString(paramMap.get(paramName).getName(),
-                                value.toString());
-                    }
+                    List<String> list = (List<String>) value;
+
                     list.add(args.get(i + 1));
                     paramMap.get(paramName).setValue(list);
                     i++;
@@ -138,14 +133,7 @@ public class OnapCliArgsParser {
                 } else if (paramMap.get(paramName).getParameterType().equals(OnapCommandParameterType.MAP)) {
                     Object value = paramMap.get(paramName).getValue();
 
-                    Map<String, String> map;
-
-                    if (value == "") {
-                        map = new HashMap<>();
-                    } else {
-                        map = convertJsonToMapString(paramMap.get(paramName).getName(),
-                                value.toString());
-                    }
+                    Map<String, String> map = (Map<String, String>) value;
 
                     String arg = args.get(i + 1);
                     String[] argArr = arg.split("=");
index eb2ca29..c3627ca 100644 (file)
@@ -21,6 +21,8 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
+import java.util.Optional;
 import java.util.Set;
 
 import org.junit.Assert;
@@ -255,7 +257,7 @@ public class OnapCliUtilsTest {
         OnapCliArgsParser.populateParams(paramslist,
                 Arrays.asList("show", "--map", "param1=value1", "--map", "param2=value2"));
 
-        Assert.assertEquals("{\"param1\":\"value1\",\"param2\":\"value2\"}", paramslist.iterator().next().getValue().toString());
+        Assert.assertEquals("{param1=value1, param2=value2}", paramslist.iterator().next().getValue().toString());
     }
 
     @Test(expected = OnapCliInvalidArgument.class)
@@ -360,4 +362,19 @@ public class OnapCliUtilsTest {
         Assert.assertEquals("--json-param", paramslist.iterator().next().getValue());
 
     }
+
+    @Test
+    public void testArrayCommandArg() throws OnapCommandException {
+        OnapCommandParameter arrParam = new OnapCommandParameter();
+        arrParam.setShortOption("q");
+        arrParam.setParameterType(OnapCommandParameterType.ARRAY);
+        arrParam.setName("array-param");
+        Set<OnapCommandParameter> paramslist = new HashSet<>();
+        paramslist.add(arrParam);
+        String[] args = new String[] { "sample-create", "-q", "test1", "-q", "test2" };
+
+        OnapCliArgsParser.populateParams(paramslist, Arrays.asList(args));
+        Assert.assertTrue(((List<String>) arrParam.getValue())
+                .containsAll(Arrays.asList("test1", "test2")));
+    }
 }
\ No newline at end of file
index 17d9c73..94baa7a 100644 (file)
@@ -126,7 +126,7 @@ public class OnapHttpCommand extends OnapCommand {
 
     private boolean isAuthRequired() {
         return !this.getService().isNoAuth()
-                && "false".equals(this.getParametersMap().get(OnapCommandHttpConstants.DEFAULT_PARAMETER_NO_AUTH).getValue())
+                && !(Boolean) (this.getParametersMap().get(OnapCommandHttpConstants.DEFAULT_PARAMETER_NO_AUTH).getValue())
                 && (this.getInfo().getCommandType().equals(OnapCommandType.CMD) ||
                         this.getInfo().getCommandType().equals(OnapCommandType.CATALOG));
     }