Fixed sonarcloud issues 00/109300/3
authorjitendra007 <jitendra.sharma1@huawei.com>
Thu, 18 Jun 2020 10:55:39 +0000 (16:25 +0530)
committerpriyanka.akhade <priyanka.akhade@huawei.com>
Thu, 9 Jul 2020 07:36:31 +0000 (13:06 +0530)
Issue-ID: CLI-270

Signed-off-by: jitendra007 <jitendra.sharma1@huawei.com>
Change-Id: Ibb52afb2fe8fe7c9be4299d1a1cb1e3d32ab0eca

32 files changed:
framework/src/main/java/org/onap/cli/fw/cmd/schema/OnapSchemaListCommand.java
framework/src/main/java/org/onap/cli/fw/cmd/schema/OnapSchemaShowCommand.java
framework/src/main/java/org/onap/cli/fw/input/OnapCommandParameter.java
framework/src/main/java/org/onap/cli/fw/output/OnapCommandResult.java
framework/src/main/java/org/onap/cli/fw/registrar/OnapCommandRegistrar.java
framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaLoader.java
framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaMerger.java
framework/src/main/java/org/onap/cli/fw/store/OnapCommandArtifactStore.java
framework/src/main/java/org/onap/cli/fw/store/OnapCommandExecutionStore.java
framework/src/main/java/org/onap/cli/fw/store/OnapCommandProfileStore.java
framework/src/main/java/org/onap/cli/fw/utils/OnapCommandDiscoveryUtils.java
framework/src/main/java/org/onap/cli/fw/utils/OnapCommandHelperUtils.java
framework/src/main/java/org/onap/cli/fw/utils/OnapCommandUtils.java
framework/src/main/java/org/onap/cli/fw/utils/ProcessRunner.java
framework/src/test/java/org/onap/cli/fw/registrar/OnapCommandRegistrarTest.java
framework/src/test/java/org/onap/cli/fw/schema/ValidateSchemaTest.java
framework/src/test/java/org/onap/cli/fw/store/OnapCommandProfileStoreTest.java
framework/src/test/java/org/onap/cli/fw/utils/OnapCommandUtilsTest.java
grpc/grpc-server/src/main/java/org/open/infc/grpc/server/OpenInterfaceGrpcServer.java
main/src/main/java/org/onap/cli/main/OnapCli.java
main/src/main/java/org/onap/cli/main/interactive/StringCompleter.java
main/src/test/java/org/onap/cli/main/OnapCliMainTest.java
profiles/command/src/main/java/org/onap/cli/fw/cmd/cmd/OpenCommandShellCmd.java
profiles/command/src/main/java/org/onap/cli/fw/cmd/schema/OnapCommandSchemaCmdLoader.java
profiles/http/src/main/java/org/onap/cli/fw/http/schema/OnapCommandSchemaHttpLoader.java
profiles/http/src/main/java/org/onap/cli/fw/http/utils/OnapCommandHttpUtils.java
profiles/http/src/test/java/org/onap/cli/fw/http/schema/OnapCommandSchemaHttpLoaderTest.java [new file with mode: 0644]
profiles/http/src/test/resources/sample-test-schema-http.yaml
profiles/snmp/src/main/java/org/onap/cli/fw/snmp/cmd/OnapSnmpCommand.java
profiles/snmp/src/main/java/org/onap/cli/fw/snmp/schema/OnapCommandSchemaSnmpLoader.java
validate/sample-mock-generator/src/main/java/org/onap/cli/http/mock/MockJsonGenerator.java
validate/sample-yaml-generator/src/main/java/org/onap/cli/sample/yaml/SampleYamlGenerator.java

index 5046f44..1273cc7 100644 (file)
@@ -39,11 +39,7 @@ public class OnapSchemaListCommand extends OnapCommand {
 
         List<OnapCommandSchemaInfo> schemas = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(true);
         for (OnapCommandSchemaInfo schema :  schemas) {
-            if (schema.isIgnore()) {
-                continue;
-            }
-
-            if (schema.getProduct().equalsIgnoreCase(product)) {
+            if (schema.getProduct().equalsIgnoreCase(product) && !schema.isIgnore()) {
                 if (service.length() > 0 && !service.equalsIgnoreCase(schema.getService())) {
                     continue;
                 }
index b7c027f..02b5e79 100644 (file)
@@ -47,7 +47,7 @@ public class OnapSchemaShowCommand extends OnapCommand {
             throw new OnapCommandNotFound(cmd, product, service);
         }
 
-        Map <String, Object> ioMap = new HashMap<String, Object>();
+        Map <String, Object> ioMap = new HashMap<>();
         ioMap.put("name", info.getCmdName());
         ioMap.put("author", info.getAuthor());
         ioMap.put("description", info.getDescription());
index d0b3c5f..6d6f95a 100644 (file)
@@ -173,10 +173,10 @@ public class OnapCommandParameter {
                     this.defaultValue = UUID.randomUUID().toString();
                     break;
                 case JSON:
-                    this.defaultValue = new String("{}");
+                    this.defaultValue = "{}";
                     break;
                 default:
-                    this.defaultValue = new String("");
+                    this.defaultValue = "";
                     break;
             }
         }
index bbe3359..b88477c 100644 (file)
@@ -39,7 +39,7 @@ public class OnapCommandResult {
      *
      * if type=TEXT, then it holds the result in text format such as help message
      */
-    private Object output = new String("");
+    private Object output = "";
 
     /*
      * Type requested by user
index c23ed2b..28344de 100644 (file)
@@ -431,7 +431,7 @@ public class OnapCommandRegistrar {
         }
     }
 
-    public List<Map<String, ?>> getTestSuite(String cmd, String product) throws OnapCommandException {
+    public List<Map<String, Object>> getTestSuite(String cmd, String product) throws OnapCommandException {
         return OnapCommandDiscoveryUtils.createTestSuite(cmd, product);
     }
 
index 4f6e4ea..04a81aa 100644 (file)
@@ -105,8 +105,8 @@ public class OnapCommandSchemaLoader {
      * @throws OnapCommandInvalidSchema        invalid schema
      * @throws OnapCommandSchemaNotFound       schema not found
      */
-    public static Map<String, ?> validateSchemaVersion(String schemaName, String version) throws OnapCommandException {
-        Map<String, ?> values = null;
+    public static Map<String, Object> validateSchemaVersion(String schemaName, String version) throws OnapCommandException {
+        Map<String, Object> values = null;
         try {
             InputStream inputStream = OnapCommandUtils.class.getClassLoader().getResourceAsStream(schemaName);
 
@@ -160,8 +160,7 @@ public class OnapCommandSchemaLoader {
                 errors.addAll(parseSchema(cmd, defaultParameterMap, validateSchema));
             }
 
-            Map<String, List<Map<String, String>>> commandYamlMap =
-                    (Map<String, List<Map<String, String>>>)validateSchemaVersion(schemaName, cmd.getSchemaVersion());
+            Map<String, ?> commandYamlMap = validateSchemaVersion(schemaName, cmd.getSchemaVersion());
 
             errors.addAll(parseSchema(cmd, commandYamlMap, validateSchema));
 
@@ -218,13 +217,13 @@ public class OnapCommandSchemaLoader {
                             HashMap<String, String> validationMap = new HashMap<>();
                             validationMap.put(INFO_TYPE, COMMAND_TYPE_VALUES);
 
-                            for (String secKey : validationMap.keySet()) {
+                            for (Map.Entry<String,String> entry : validationMap.entrySet()) {
+                                String secKey=entry.getKey();
                                 if (infoMap.containsKey(secKey)) {
-                                    Object obj = infoMap.get(secKey);
-                                    if (obj == null) {
+                                    String value = infoMap.get(secKey);
+                                    if (value == null) {
                                         exceptionList.add("Attribute '" + secKey + "' under '" + INFO + "' is empty");
                                     } else {
-                                        String value = String.valueOf(obj);
                                         if (!OnapCommandConfig.getCommaSeparatedList(validationMap.get(secKey)).contains(value)) {
                                             exceptionList.add("Attribute '" + secKey + "' contains invalid value. Valide values are "
                                                     + OnapCommandConfig.getCommaSeparatedList(validationMap.get(key))); //
@@ -267,6 +266,7 @@ public class OnapCommandSchemaLoader {
                                     Object ignore = infoMap.get(key1);
                                     info.setIgnore(ignore.toString().equalsIgnoreCase(OnapCommandConstants.BOOLEAN_TRUE));
                                     break;
+                                default : // Do nothing
                             }
                         }
 
@@ -350,12 +350,10 @@ public class OnapCommandSchemaLoader {
                                         break;
 
                                     case IS_SECURED:
-                                        if (validate) {
-                                            if (!OnapCommandUtils.validateBoolean(String.valueOf(parameter.get(key2)))) {
+                                            if (validate && !OnapCommandUtils.validateBoolean(String.valueOf(parameter.get(key2)))) {
                                                 exceptionList.add(OnapCommandUtils.invalidBooleanValueMessage(parameter.get(NAME),
                                                         IS_SECURED, String.valueOf(parameter.get(key2))));
                                             }
-                                        }
 
                                         param.setSecured(BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2))));
                                         break;
@@ -370,15 +368,14 @@ public class OnapCommandSchemaLoader {
                                         break;
 
                                     case IS_DEFAULT_PARAM:
-                                        if (validate) {
-                                            if (!OnapCommandUtils.validateBoolean(String.valueOf(parameter.get(key2)))) {
+                                            if (validate && !OnapCommandUtils.validateBoolean(String.valueOf(parameter.get(key2)))) {
                                                 exceptionList.add(OnapCommandUtils.invalidBooleanValueMessage(parameter.get(NAME),
                                                         IS_DEFAULT_PARAM, String.valueOf(parameter.get(key2))));
                                             }
-                                        }
 
                                         param.setDefaultParam(BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2))));
                                         break;
+                                    default : // Do nothing
                                 }
                             }
 
@@ -455,34 +452,33 @@ public class OnapCommandSchemaLoader {
                                                     break;
 
                                                 case IS_SECURED:
-                                                    if (validate) {
-                                                        if (!OnapCommandUtils.validateBoolean(String.valueOf(map.get(key4)))) {
+                                                        if (validate && !OnapCommandUtils.validateBoolean(String.valueOf(map.get(key4)))) {
                                                             exceptionList.add(OnapCommandUtils.invalidBooleanValueMessage(ATTRIBUTES,
                                                                     IS_SECURED, String.valueOf(map.get(key4))));
                                                         }
-                                                    }
                                                     attr.setSecured(BOOLEAN_TRUE.equals(String.valueOf(map.get(key4))));
                                                     break;
 
                                                 case IS_DEFAULT_ATTR:
-                                                    if (validate) {
-                                                        if (!OnapCommandUtils.validateBoolean(String.valueOf(map.get(key4)))) {
+                                                        if (validate && !OnapCommandUtils.validateBoolean(String.valueOf(map.get(key4)))) {
                                                             exceptionList.add(OnapCommandUtils.invalidBooleanValueMessage(ATTRIBUTES,
                                                                     IS_DEFAULT_ATTR, String.valueOf(map.get(key4))));
                                                         }
-                                                    }
                                                     attr.setDefaultAttr(BOOLEAN_TRUE.equals(String.valueOf(map.get(key4))));
                                                     break;
+                                                default : // Do nothing
                                             }
 
                                         }
                                         cmd.getResult().getRecords().add(attr);
                                     }
                                     break;
+                                default : // Do nothing
                             }
                         }
                     }
                     break;
+                default : // Do nothing
             }
         }
 
@@ -515,7 +511,7 @@ public class OnapCommandSchemaLoader {
      * @throws OnapCommandInvalidSchema
      *             exception
      */
-    public static Map<String, ?> loadSchema(InputStream stream, String schemaName) throws OnapCommandInvalidSchema  {
+    public static Map<String, Object> loadSchema(InputStream stream, String schemaName) throws OnapCommandInvalidSchema  {
         return OnapCommandDiscoveryUtils.loadYaml(stream);
 
     }
index 97ca4c1..6ad0274 100644 (file)
@@ -114,9 +114,7 @@ public class OnapCommandSchemaMerger {
             String nameN = (String)oN.getOrDefault(OnapCommandConstants.NAME, null);
 
             //Name should be existing in the map, otherwise continue as don't know how to compare
-            if (nameN == null) {
-                continue;
-            }
+            if (nameN != null) {
 
             boolean existing = false;
             for (Object e: originalList) {
@@ -124,10 +122,6 @@ public class OnapCommandSchemaMerger {
                 String nameE = (String)oE.getOrDefault(OnapCommandConstants.NAME, null);
 
                 //Name should be existing in the map, otherwise continue as don't know how to compare
-                if (nameE == null) {
-                    continue;
-                }
-
                 if (nameN.equals(nameE)) {
                     for (Entry<String, Object> oNe : oN.entrySet()) {
                            oE.put(oNe.getKey(), oNe.getValue());
@@ -141,6 +135,7 @@ public class OnapCommandSchemaMerger {
                 originalList.add(o);
             }
         }
+        }
     }
 }
 
index 5938a11..5879715 100644 (file)
@@ -56,7 +56,7 @@ public class OnapCommandArtifactStore {
 
     private SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
 
-    private static String SEPARATOR = "__";
+    private static final String SEPARATOR = "__";
 
     public static class Artifact {
         private String name;
@@ -255,8 +255,10 @@ public class OnapCommandArtifactStore {
         if (!aFile.exists()) {
             throw new OnapCommandArtifactNotFound(name, category);
         }
-        if(!aFile.delete()){
-            log.error("Failed to delete the artifact {}", aFile.getAbsolutePath());
+        try {
+            Files.delete(Paths.get(storePath));
+        } catch (IOException e) {
+            log.error("Failed to delete the artifact " + aFile.getAbsolutePath());
         }
     }
 
index b0ebbda..15996a8 100644 (file)
@@ -19,6 +19,9 @@ package org.onap.cli.fw.store;
 import java.io.File;
 import java.io.FilenameFilter;
 import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -56,7 +59,7 @@ public class OnapCommandExecutionStore {
 
     private SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
 
-    private static String SEPARATOR = "__";
+    private static final String SEPARATOR = "__";
 
     private enum SearchMode {
         FIND,
@@ -65,11 +68,11 @@ public class OnapCommandExecutionStore {
 
     }
 
-    private static SearchMode SEARCH_MODE = SearchMode.FILE;
+    private static SearchMode searchMode = SearchMode.FILE;
     static {
         String mode = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_EXECUTION_SEARCH_MODE);
         if (mode.equalsIgnoreCase(SearchMode.FIND.name()))
-            SEARCH_MODE = SearchMode.FIND;
+            searchMode = SearchMode.FIND;
     }
 
     public static class ExecutionStoreContext {
@@ -279,9 +282,11 @@ public class OnapCommandExecutionStore {
                 FileUtils.touch(new File(context.getStorePath() + File.separator + COMPLETED));
             else
                 FileUtils.touch(new File(context.getStorePath() + File.separator + FAILED));
-
-            if(!new File(context.getStorePath() + File.separator + IN_PROGRESS).delete()){
-                log.error("Failed to delete {}", context.getStorePath() + File.separator + IN_PROGRESS);
+            Path path= Paths.get(context.getStorePath() + File.separator + IN_PROGRESS);
+            try {
+                Files.delete(path);
+            } catch (IOException e) {
+                log.error("Failed to delete "+ context.getStorePath() + File.separator + IN_PROGRESS);
             }
         } catch (IOException e) {
             log.error("Failed to store the execution end details {}", context.storePath);
@@ -334,7 +339,7 @@ public class OnapCommandExecutionStore {
 
         try {
             List <String> dirs = new ArrayList<>();
-            if (System.getProperty("os.name").toLowerCase().startsWith("windows") || SEARCH_MODE.equals(SearchMode.FILE)) {
+            if (System.getProperty("os.name").toLowerCase().startsWith("windows") || searchMode.equals(SearchMode.FILE)) {
                 for (File f: new File(getBasePath()).listFiles()) {
                     if(search.containsKey(EXECUTIONID)) {
                         if (f.getName().startsWith(search.get(EXECUTIONID)))
@@ -347,7 +352,6 @@ public class OnapCommandExecutionStore {
                         if (f.getName().startsWith(search.get(REQUESTID)))
                                 dirs.add(f.getAbsolutePath());
 
-                        continue;
                     }
 
                     else
@@ -449,12 +453,9 @@ public class OnapCommandExecutionStore {
     }
 
     private File getExecutionDir(String executionId) throws OnapCommandExecutionNotFound {
-        File []f =  new File(getBasePath()).listFiles(new FilenameFilter() {
-
-            @Override
-            public boolean accept(File dir, String name) {
-                return name.startsWith(executionId);
-            }
+        File []f =  new File(getBasePath()).listFiles((dir, name) -> {
+            if (name.startsWith(executionId)) return true;
+            return false;
         });
 
         if (f.length == 0) {
index 139521e..677c45e 100644 (file)
@@ -21,6 +21,8 @@ import static org.onap.cli.fw.conf.OnapCommandConstants.DATA_PATH_PROFILE_JSON;
 import java.io.File;
 import java.io.FilenameFilter;
 import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -96,11 +98,9 @@ public class OnapCommandProfileStore {
     }
 
     public void remove(String productVersion, String paramName) {
-        if (paramCache.containsKey(productVersion)) {
-            if (paramCache.get(productVersion).containsKey(paramName)) {
+            if (paramCache.containsKey(productVersion) && paramCache.get(productVersion).containsKey(paramName)) {
                 paramCache.get(productVersion).remove(paramName);
             }
-        }
 
         this.persist();
     }
@@ -205,23 +205,18 @@ public class OnapCommandProfileStore {
     public void removeProfile(String profile) {
          String dataDir = getDataStorePath();
          File file = new File(dataDir + File.separator + profile + DATA_PATH_PROFILE_JSON);
-         if (file.exists()) {
-            if(!file.delete()){
-                log.error("Failed to delete profile {}", file.getAbsolutePath());
+        try {
+            Files.delete(Paths.get(dataDir + File.separator + profile + DATA_PATH_PROFILE_JSON));
+        } catch (IOException e) {
+                log.error("Failed to delete profile {}"+file.getAbsolutePath());
             }
-         }
     }
 
     public List<String> getProfiles() {
         List<String> profiles = new ArrayList<>();
 
         String dataDir = getDataStorePath();
-        for (File file: new File(dataDir).listFiles(new FilenameFilter() {
-            @Override
-            public boolean accept(File dir, String name) {
-                return name.endsWith(DATA_PATH_PROFILE_JSON);
-            }
-        })) {
+        for (File file: new File(dataDir).listFiles((dir, name) -> name.endsWith(DATA_PATH_PROFILE_JSON))) {
             String profile = file.getName().substring(0, file.getName().indexOf(DATA_PATH_PROFILE_JSON));
             profiles.add(profile);
         }
index 0db9695..b299907 100644 (file)
@@ -68,6 +68,10 @@ import java.io.InputStreamReader;
 import java.io.FileInputStream;
 
 public class OnapCommandDiscoveryUtils {
+    private OnapCommandDiscoveryUtils() {
+        throw new IllegalStateException("Utility class");
+    }
+
     private static Gson gson = new GsonBuilder().serializeNulls().create();
 
     /**
@@ -214,8 +218,8 @@ public class OnapCommandDiscoveryUtils {
      * @throws OnapCommandInvalidSchema
      *             exception
      */
-    public static Map<String, ?> loadSchema(Resource resource) throws OnapCommandInvalidSchema {
-        Map<String, ?> values = null;
+    public static Map<String, Object> loadSchema(Resource resource) throws OnapCommandInvalidSchema {
+        Map<String, Object> values = null;
         try {
             values = loadYaml(resource.getInputStream());
         } catch (Exception e) {
@@ -336,22 +340,18 @@ public class OnapCommandDiscoveryUtils {
 
                         Object obj = resourceMap.get(OPEN_CLI_SCHEMA_VERSION);
                         if (obj == null) {
-                            OnapCommandUtils.log.info("Invalid Schema yaml {}", schema.getSchemaURI());
-                            continue;
+                            OnapCommandUtils.log.info("Invalid Schema yaml {}" + schema.getSchemaURI());
                         }
-
+                        else{
                         schema.setVersion(obj.toString());
 
                         if (!schema.getVersion().equalsIgnoreCase(OnapCommandConstants.OPEN_CLI_SCHEMA_VERSION_VALUE_1_0)) {
-                            OnapCommandUtils.log.info("Unsupported Schema version found {}", schema.getSchemaURI());
-                            continue;
+                            OnapCommandUtils.log.info("Unsupported Schema version found {} " + schema.getSchemaURI());
                         }
+                        else{
 
                         //There are schema like default input parameters and does not have command name
-                        if (resourceMap.get(NAME) == null) {
-                            continue;
-                        }
-
+                        if (resourceMap.get(NAME) != null) {
                         schema.setSchemaName(resource.getFilename());
                         schema.setCmdName((String) resourceMap.get(NAME));
 
@@ -401,6 +401,9 @@ public class OnapCommandDiscoveryUtils {
 
                         extSchemas.add(schema);
                     }
+                        }
+                        }
+                    }
                 }
             }
         } catch (IOException e) {
@@ -481,9 +484,10 @@ public class OnapCommandDiscoveryUtils {
 
     }
 
-    public static List<Map<String, ?>> createTestSuite(String cmd, String version) throws OnapCommandException {
+    public static List<Map<String, Object>> createTestSuite(String cmd, String version) throws OnapCommandException {
+
+        ArrayList<Map<String, Object>> testSamples = new ArrayList();
 
-        ArrayList<Map<String, ?>> testSamples = new ArrayList<>();
 
         List<Resource> resources = new ArrayList<>();
         OnapCommandSchemaInfo schemaInfo =  getSchemaInfo(cmd, version);
@@ -509,9 +513,9 @@ public class OnapCommandDiscoveryUtils {
             Map<String, Map<String, String>> samples = (Map<String, Map<String, String>>) stringMap
                     .get(OnapCommandConstants.VERIFY_SAMPLES);
 
-            for (String sampleId : samples.keySet()) {
-
-                Map<String, String> sample = samples.get(sampleId);
+            for (Map.Entry<String,Map<String, String>> entry : samples.entrySet()) {
+                String sampleId=entry.getKey();
+                Map<String, String> sample = entry.getValue();
 
                 List<String> inputArgs = new ArrayList<>();
                 if (sample.get(OnapCommandConstants.VERIFY_INPUT) != null) {
@@ -540,8 +544,8 @@ public class OnapCommandDiscoveryUtils {
      * @throws OnapCommandInvalidSchema
      *             exception
      */
-    public static Map<String, ?> loadYaml(Resource resource) throws OnapCommandInvalidSchema {
-        Map<String, ?> values = null;
+    public static Map<String, Object> loadYaml(Resource resource) throws OnapCommandInvalidSchema {
+        Map<String, Object> values = null;
         try {
             values = loadYaml(resource.getInputStream());
         } catch (Exception e) {
@@ -558,8 +562,8 @@ public class OnapCommandDiscoveryUtils {
      * @throws OnapCommandInvalidSchema
      *             exception
      */
-    public static Map<String, ?> loadYaml(String filePath) throws OnapCommandInvalidSchema {
-        Map<String, ?> values = null;
+    public static Map<String, Object> loadYaml(String filePath) throws OnapCommandInvalidSchema {
+        Map<String, Object> values = null;
         try {
             values = loadYaml(new FileInputStream(new File(filePath)));
         } catch (Exception e) {
@@ -577,11 +581,11 @@ public class OnapCommandDiscoveryUtils {
      * @throws OnapCommandInvalidSchema
      *             exception
      */
-    public static Map<String, ?> loadYaml(InputStream inputStream) throws OnapCommandInvalidSchema {
-        Map<String, ?> values = null;
+    public static Map<String, Object> loadYaml(InputStream inputStream) throws OnapCommandInvalidSchema {
+        Map<String, Object> values = null;
         try(InputStreamReader inputStreamReader = new InputStreamReader(inputStream);){
             YamlReader reader = new YamlReader(inputStreamReader);
-            values = (Map<String, ?>) reader.read();
+            values = (Map<String, Object>) reader.read();
             } catch (IOException e) {
                 throw new OnapCommandInvalidSchema(inputStream.getClass().getName(),e.getMessage());
             }
index e115088..98a4af2 100644 (file)
@@ -37,6 +37,10 @@ import org.onap.cli.fw.output.OnapCommandResultType;
 
 public class OnapCommandHelperUtils {
 
+    private OnapCommandHelperUtils() {
+        throw new IllegalStateException("Utility class");
+    }
+
     /**
      * Returns the build time from manifest.mf
      */
index ea8e648..60bf2d2 100644 (file)
@@ -252,13 +252,10 @@ public class OnapCommandUtils {
 
             String value = "";
 
-            switch (splEntry) {
-                case OnapCommandConstants.SPL_ENTRY_UUID:
+            if (OnapCommandConstants.SPL_ENTRY_UUID.equals(splEntry)) {
                     value = UUID.randomUUID().toString();
-                    break;
-
-                default:
-
+            }
+                else{
                     if (splEntry.startsWith(OnapCommandConstants.SPL_ENTRY_ENV)) {
                         //start to read after env:ENV_VAR_NAME
                         String envVarName = splEntry.substring(4);
index 69df607..62f5c9a 100644 (file)
@@ -118,27 +118,25 @@ public class ProcessRunner {
             readError = true;
         }
 
-        final OutputStream stdout = this.getStdout();
-        final OutputStream stderr = this.getStderr();
+        final OutputStream stdoutLocal = this.getStdout();
+        final OutputStream stderrLocal = this.getStderr();
 
         final InputStream stdoutP = p.getInputStream();
         final InputStream stderrP = p.getErrorStream();
 
-        Thread outThread = new Thread(new Runnable() {
-            public void run() {
-                try {
-                    IOUtils.copy(stdoutP, stdout);
-                } catch (IOException e) { // NOSONAR
-                }
+        Thread outThread = new Thread(() -> {
+            try {
+                IOUtils.copy(stdoutP, stdoutLocal);
+            } catch (IOException e) { //NOSONAR
+                // Do nothing
             }
         });
 
-        Thread errThread = new Thread(new Runnable() {
-            public void run() {
-                try {
-                    IOUtils.copy(stderrP, stderr);
-                } catch (IOException e) { // NOSONAR
-                }
+        Thread errThread = new Thread(() -> {
+            try {
+                IOUtils.copy(stderrP, stderrLocal);
+            } catch (IOException e) { //NOSONAR
+                // Do nothing
             }
         });
 
index 800a6c9..2b3c62b 100644 (file)
@@ -24,6 +24,8 @@ import static org.junit.Assert.fail;
 import java.io.File;
 import java.net.URL;
 import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -95,6 +97,11 @@ public class OnapCommandRegistrarTest {
         cmd.printVersion();
         registrar.listCommands();
     }
+    @Test
+    public void getTestSuiteTest() throws OnapCommandException {
+        List<Map<String, Object>> cmds =registerar.getTestSuite("schema-validate","open-cli");
+        assertTrue(cmds.size() >= 1);
+    }
 }
 
 @OnapCommandSchema(schema = "sample-test-schema.yaml")
index 4c64ca2..e951793 100644 (file)
@@ -18,7 +18,10 @@ package org.onap.cli.fw.schema;
 
 import static org.junit.Assert.assertTrue;
 
+import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
 import org.junit.Test;
 import org.onap.cli.fw.cmd.OnapCommand;
@@ -137,4 +140,38 @@ public class ValidateSchemaTest {
         assertTrue(errorList2.size() > 0);
     }
 
+    @Test
+    public void parseSchemaTest() throws OnapCommandException {
+        OnapCommand cmd = new OnapCommand() {
+            @Override
+            protected void run() throws OnapCommandException {}
+        };
+        Map<String, Object> values=new HashMap<>();
+        List<Map<String, Object>> list=new ArrayList<>();
+        Map<String,Object> paraValues=new HashMap<>();
+        paraValues.put("is_secured","yes");
+        paraValues.put("is_default_param","yes");
+        list.add(paraValues);
+        values.put("parameters",list);
+        assertTrue(OnapCommandSchemaLoader.parseSchema(cmd,values,true).size()==2);
+
+    }
+    @Test
+    public void parseSchema2Test() throws OnapCommandException {
+        OnapCommand cmd = new OnapCommand() {
+            @Override
+            protected void run() throws OnapCommandException {}
+        };
+        Map<String, Object> values=new HashMap<>();
+        List<Map<String, Object>> list=new ArrayList<>();
+        Map<String,Object> paraValues=new HashMap<>();
+        Map<String, Object> attributesValues=new HashMap<>();
+        paraValues.put("is_secured","yes");
+        paraValues.put("is_default_attr","yes");
+        list.add(paraValues);
+        attributesValues.put("attributes",list);
+        values.put("results",attributesValues);
+        assertTrue(OnapCommandSchemaLoader.parseSchema(cmd,values,true).size()==2);
+
+    }
 }
index 1635b1b..c2f2fe1 100644 (file)
@@ -79,7 +79,11 @@ public class OnapCommandProfileStoreTest {
         assertNotNull(onapCommandProfileStore.getParams("abc"));
     }
 
-
+    @Test
+    public void removeTest() {
+        onapCommandProfileStore.add("abc", "abc", "abc");
+        onapCommandProfileStore.remove("abc","abc");
+    }
 
     @AfterClass
     public static void tearDown() throws Exception {
index b7da1c2..d7bd805 100644 (file)
@@ -43,6 +43,7 @@ import org.onap.cli.fw.schema.OnapCommandSchema;
 import org.onap.cli.fw.schema.OnapCommandSchemaInfo;
 import org.onap.cli.fw.schema.OnapCommandSchemaLoader;
 
+import java.io.File;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -428,6 +429,11 @@ public class OnapCommandUtilsTest {
         List<Class<OnapCommand>> cmds = OnapCommandDiscoveryUtils.discoverCommandPlugins();
         assertTrue(cmds.size() >= 1);
     }
+    @Test
+    public void createTestSuiteTest() throws OnapCommandException {
+        List<Map<String, Object>> cmds = OnapCommandDiscoveryUtils.createTestSuite("schema-validate","open-cli");
+        assertTrue(cmds.size() >= 1);
+    }
 
     @Test
     public void sortTest() {
@@ -544,4 +550,10 @@ public class OnapCommandUtilsTest {
           assertTrue(mapExample.get("key2").equals("paramB"));
    }
 
+    @Test
+    public void loadYamlTest() throws OnapCommandInvalidSchema {
+        File file=new File("src/test/resources/sample-test-info.yaml");
+        Map<String, Object> values= OnapCommandDiscoveryUtils.loadYaml(file.getAbsolutePath());
+        assertEquals(values.get("name"),"sample-test-info");
+    }
 }
index 6bca7b3..427bab7 100644 (file)
@@ -213,10 +213,8 @@ public class OpenInterfaceGrpcServer {
                     cmd.getParametersMap().get(OnapCommandConstants.RPC_MODE).setValue(OnapCommandConstants.RPC_MODE_RUN_RPC);
                 }
 
-                if (!cmd.isRpc()) {
                     //Start the execution
-                    if (req.getRequestId() != null && !req.getRequestId().isEmpty()) {
-                        if (!(cmd.getInfo().getProduct().equalsIgnoreCase("open-cli") &&
+                        if (!cmd.isRpc()&&req.getRequestId() != null && !req.getRequestId().isEmpty()&&!(cmd.getInfo().getProduct().equalsIgnoreCase("open-cli") &&
                                 cmd.getName().equalsIgnoreCase("execution-list"))) {
                         String input = cmd.getArgsJson(true);
                         executionStoreContext = OnapCommandExecutionStore.getStore().storeExectutionStart(
@@ -227,8 +225,6 @@ public class OpenInterfaceGrpcServer {
                                 profile,
                                 input);
                         }
-                    }
-                }
                 cmd.setExecutionContext(executionStoreContext);
                 cmd.execute();
 
index 4c12d7e..b11b1b2 100644 (file)
@@ -287,7 +287,7 @@ public class OnapCli {
                 .filter(e -> e.getName().equals(OnapCommandConstants.VERIFY_CONTEXT_PARAM))
                 .findFirst();
 
-        List<Map<String, ?>> testSuite = OnapCommandRegistrar.getRegistrar().getTestSuite(
+        List<Map<String, Object>> testSuite = OnapCommandRegistrar.getRegistrar().getTestSuite(
                 cmd.getName(),
                 cmd.getInfo().getProduct());
 
@@ -544,8 +544,7 @@ public class OnapCli {
                 OnapCliArgsParser.populateParams(cmd.getParameters(), this.args);
 
                 //start the execution
-                if (this.requestId != null && this.product != null && !this.requestId.isEmpty()) {
-                    if (!(this.product.equalsIgnoreCase("open-cli") &&
+                    if (this.requestId != null && this.product != null && !this.requestId.isEmpty()&& !(this.product.equalsIgnoreCase("open-cli") &&
                             this.cmdName.equalsIgnoreCase("execution-list"))) {
                         String input = cmd.getArgsJson(true);
                         executionStoreContext = OnapCommandExecutionStore.getStore().storeExectutionStart(
@@ -556,7 +555,6 @@ public class OnapCli {
                                 this.profile,
                                 input);
                     }
-                }
 
                 cmd.setExecutionContext(executionStoreContext);
                 OnapCommandResult result = cmd.execute();
index cf2a6c5..115e4f4 100644 (file)
@@ -29,7 +29,7 @@ import java.util.TreeSet;
  *
  */
 public class StringCompleter implements Completer {
-    private final SortedSet<String> strings = new TreeSet<String>();
+    private final SortedSet<String> strings = new TreeSet<>();
 
     /**
      * Public Constructor takes collection of strings.
index 0fb8328..c1e0509 100644 (file)
@@ -30,7 +30,11 @@ import org.onap.cli.fw.error.OnapCommandException;
 import org.onap.cli.fw.error.OnapCommandHelpFailed;
 import org.onap.cli.fw.registrar.OnapCommandRegistrar;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
+import java.util.Arrays;
 import org.onap.cli.fw.error.OnapCommandInvalidSchema;
 import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils;
 import static org.junit.Assert.assertFalse;
@@ -222,4 +226,23 @@ public class OnapCliMainTest {
         Map<String,?> map = OnapCommandDiscoveryUtils.loadYaml("src/test/resources/open-cli-schema/sample-test-schema.yaml");
         assertFalse(map.isEmpty());
     }
+    @Test
+    public void testverifyCommand() throws OnapCommandException {
+        cli = new OnapCli(new String[] {"schema-validate","--verify" });
+      new MockUp<OnapCommandRegistrar>(){
+            @Mock
+            public List<Map<String, Object>> getTestSuite(String cmd, String product) throws OnapCommandException {
+                List<Map<String, Object>> list=new ArrayList<>();
+                Map<String,Object>map=new HashMap<>();
+                map.put("output","output");
+                map.put("input", Arrays.asList(new String[]{"--verify"}));
+                map.put("sampleid","sample1");
+                map.put("samplefileid","schema-validate-sample.yaml");
+                map.put("moco","schema-validate-moco.json");
+                list.add(map);
+                return list;
+            }
+        };
+        cli.handleCommand();
+    }
 }
index dd2c26c..3bb2606 100644 (file)
@@ -163,32 +163,32 @@ public class OpenCommandShellCmd extends OnapCommand {
         //Process command
         String []cmd = commandLine.toArray(new String []{});
         String cwd = this.getWd();
-        List <String> envs = new ArrayList<>();
+        List <String> envList = new ArrayList<>();
 
         //add current process environments to sub process
         for (Map.Entry<String, String> env: System.getenv().entrySet()) { //NOSONAR
-            envs.add(env.getKey() + "=" + env.getValue());
+            envList.add(env.getKey() + "=" + env.getValue());
         }
 
         //add oclip specific environment variables
         if (this.getExecutionContext() != null) {
-            envs.add("OPEN_CLI_REQUEST_ID=" + this.getExecutionContext().getRequestId());
+            envList.add("OPEN_CLI_REQUEST_ID=" + this.getExecutionContext().getRequestId());
             if (this.getExecutionContext().getProfile() != null) {
-                envs.add("OPEN_CLI_PROFILE=" + this.getExecutionContext().getProfile());
+                envList.add("OPEN_CLI_PROFILE=" + this.getExecutionContext().getProfile());
             }
             if (OnapCommandRegistrar.getRegistrar().getHost() != null) {
-                envs.add("OPEN_CLI_RPC_HOST=" + OnapCommandRegistrar.getRegistrar().getHost());
-                envs.add("OPEN_CLI_RPC_PORT=" + OnapCommandRegistrar.getRegistrar().getPort());
+                envList.add("OPEN_CLI_RPC_HOST=" + OnapCommandRegistrar.getRegistrar().getHost());
+                envList.add("OPEN_CLI_RPC_PORT=" + OnapCommandRegistrar.getRegistrar().getPort());
             }
         }
 
         for (String env: this.getEnvs().keySet()) {
-            envs.add(env + "=" + this.getEnvs().get(env));
+            envList.add(env + "=" + this.getEnvs().get(env));
         }
 
         ProcessRunner pr = new ProcessRunner(
                 cmd,
-                (!envs.isEmpty()) ? envs.toArray(new String []{}) : null,
+                (!envList.isEmpty()) ? envList.toArray(new String []{}) : null,
                 cwd);
         FileOutputStream stdoutStream = null;
         FileOutputStream stderrStream = null;
index 1eeadec..2d40806 100644 (file)
@@ -98,6 +98,7 @@ public class OnapCommandSchemaCmdLoader {
                     case OnapCommandCmdConstants.PASS_CODE:
                         cmd.setPassCodes((ArrayList) valMap.get(key1));
                         break;
+                    default : // Do nothing
                 }
             }
         }
index d064547..e7a643a 100644 (file)
@@ -68,8 +68,8 @@ public class OnapCommandSchemaHttpLoader {
                 errors.addAll(OnapCommandSchemaLoader.parseSchema(cmd, defaultParameterMap, validateSchema));
             }
 
-            Map<String, List<Map<String, String>>> commandYamlMap =
-                    (Map<String, List<Map<String, String>>>) OnapCommandSchemaLoader.validateSchemaVersion(schemaName, cmd.getSchemaVersion());
+            Map<String, ?> commandYamlMap =
+                    OnapCommandSchemaLoader.validateSchemaVersion(schemaName, cmd.getSchemaVersion());
 
             errors.addAll(parseHttpSchema(cmd, commandYamlMap, validateSchema));
 
@@ -162,20 +162,18 @@ public class OnapCommandSchemaHttpLoader {
                                             Map<String, Object> context = (Map<String, Object>) map.get(key2);
 
                                             for (String key: context.keySet()) {
-                                                switch (key) {
-                                                    case OnapCommandHttpConstants.CONTEXT_REMOVE_EMPTY_JSON_NODES:
+                                                if (OnapCommandHttpConstants.CONTEXT_REMOVE_EMPTY_JSON_NODES.equals(key)) {
                                                         Boolean flag = Boolean.valueOf(context.get(OnapCommandHttpConstants.CONTEXT_REMOVE_EMPTY_JSON_NODES).toString());
                                                         cmd.getInput().getContext().put(OnapCommandHttpConstants.CONTEXT_REMOVE_EMPTY_JSON_NODES, flag.toString());
-                                                        break;
                                                 }
                                             }
 
-
                                             break;
                                         case OnapCommandHttpConstants.MULTIPART_ENTITY_NAME:
                                             Object multipartEntityName = map.get(key2);
                                             cmd.getInput().setMultipartEntityName(multipartEntityName.toString());
                                             break;
+                                        default : // Do nothing
                                     }
                                 }catch (Exception ex) {
                                     OnapCommandUtils.throwOrCollect(new OnapCommandInvalidSchema(cmd.getSchemaName(), ex), errorList, validate);
@@ -235,6 +233,7 @@ public class OnapCommandSchemaHttpLoader {
                                             Object mode = serviceMap.get(key);
                                             srv.setMode(mode.toString());
                                             break;
+                                        default : // Do nothing
                                     }
                                 }
 
@@ -260,6 +259,7 @@ public class OnapCommandSchemaHttpLoader {
                         case OnapCommandHttpConstants.SAMPLE_RESPONSE:
                             // (mrkanag) implement sample response handling
                             break;
+                        default : // Do nothing
                     }
                 }
             }
@@ -353,10 +353,8 @@ public class OnapCommandSchemaHttpLoader {
 
         for (Object successCode : requestSuccessCodes) {
             Integer code = Integer.valueOf(String.valueOf(successCode));
-            if (code < 200 || code >= 300) {
-                if ( code != 404) {
+            if ((code < 200 || code >= 300) && code != 404) {
                     errorList.add(OnapCommandHttpConstants.HTTP_SUCCESS_CODE_INVALID);
-                }
             }
         }
 
index ec2f572..dcc3082 100644 (file)
@@ -52,9 +52,11 @@ import net.minidev.json.JSONArray;
 
 public class OnapCommandHttpUtils {
 
-    static Logger LOG = LoggerFactory.getLogger(OnapCommandHttpUtils.class);
+    static Logger log = LoggerFactory.getLogger(OnapCommandHttpUtils.class);
     private static Gson gson = new GsonBuilder().serializeNulls().create();
-
+    private OnapCommandHttpUtils() {
+        throw new IllegalStateException("Utility class");
+    }
     /**
      * Set argument to param value.
      *
diff --git a/profiles/http/src/test/java/org/onap/cli/fw/http/schema/OnapCommandSchemaHttpLoaderTest.java b/profiles/http/src/test/java/org/onap/cli/fw/http/schema/OnapCommandSchemaHttpLoaderTest.java
new file mode 100644 (file)
index 0000000..a6fbe9a
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2020 Huawei Technologies Co., Ltd.
+ *
+ * Licensed 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.onap.cli.fw.http.schema;
+
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class OnapCommandSchemaHttpLoaderTest {
+    @Test
+    public void validateHttpSccessCodesTest(){
+       List<String> errorList= new ArrayList<>();
+        List<Object> requestSuccessCodes=new ArrayList<>();
+        requestSuccessCodes.add("101");
+        OnapCommandSchemaHttpLoader.validateHttpSccessCodes(errorList,requestSuccessCodes);
+    }
+}
index c78dcea..ad25c15 100644 (file)
@@ -89,6 +89,8 @@ http:
     method: POST
     body: '{"serviceName":"${service-name}","version":"${service-version}","url":"${service-url}","protocol":"REST","visualRange":"1","lb_policy":"hash","nodes":[{"ip":"${node-ip}","port":"${node-port}","ttl":0}]}'
     headers:
+    context:
+      remove_empty_node: true
     queries:
       createOrUpdate: ${create-or-update}
   success_codes:
index 3e841e7..4fc4753 100644 (file)
@@ -116,9 +116,7 @@ public class OnapSnmpCommand extends OnapCommand {
 
             String[] oidStrArr = oids.toArray(new String[oids.size()]);
 
-            switch (this.command) {
-
-                case OnapCommandSnmpConstants.SNMP_CMD_GET:
+            if (OnapCommandSnmpConstants.SNMP_CMD_GET.equals(this.command)) {
                     ResponseEvent responseEvent = snmp.send(getPDU(PDU.GET, oidStrArr), getTarget(), null);
                     if ( responseEvent != null) {
                         if (responseEvent.getResponse().getErrorStatus() == PDU.noError) {
@@ -138,10 +136,6 @@ public class OnapSnmpCommand extends OnapCommand {
                     } else {
                         throw new OnapSnmpErrorResponse("Failed to send SNMP GET command");
                     }
-                    break;
-
-                default:
-                    break;
             }
             snmp.close();
         } catch (IOException ex) {
index ca3f44e..0d70820 100644 (file)
@@ -27,7 +27,9 @@ import org.onap.cli.fw.snmp.conf.OnapCommandSnmpConstants;
 import org.onap.cli.fw.utils.OnapCommandUtils;
 
 public class OnapCommandSchemaSnmpLoader {
-
+    private OnapCommandSchemaSnmpLoader() {
+        throw new IllegalStateException("Utility class");
+    }
     private static List<String> validateSnmpSchemaSection(Map<String, Object> values) {
         ArrayList<String> errorList = new ArrayList<>();
 
@@ -61,7 +63,7 @@ public class OnapCommandSchemaSnmpLoader {
 
                     case OnapCommandSnmpConstants.SNMP_COMMAND:
                         cmd.setCommand((String) entry.getValue());
-
+                        break;
                     default:
                         break;
                 }
index ffc7c7e..780ad69 100644 (file)
@@ -25,7 +25,9 @@ import java.io.FileWriter;
 
 public class MockJsonGenerator {
     private static Gson gson = new GsonBuilder().serializeNulls().create();
-
+    private MockJsonGenerator() {
+        throw new IllegalStateException("Utility class");
+    }
     public static void generateMocking(MockRequest mockRequest, MockResponse mockResponse, String jsonFilePath) throws IOException {
 
         MockObject mockObject = new MockObject();
index bc8f456..48ae7db 100644 (file)
@@ -26,7 +26,9 @@ import java.util.stream.Collectors;
 public class SampleYamlGenerator {
 
     static int nTab;
-
+    private SampleYamlGenerator() {
+        throw new IllegalStateException("Utility class");
+    }
     public static void generateSampleYaml(String cmdName, List<String> input, String output, String version,
             String targetPath, boolean debug, String name) throws IOException {