Code Improvements-Sonar Issue Fixes 09/109309/2
authorSravanKumarGunda <sravan.kumar1@huawei.com>
Thu, 18 Jun 2020 13:35:44 +0000 (19:05 +0530)
committerSravanKumarGunda <sravan.kumar1@huawei.com>
Thu, 2 Jul 2020 10:32:50 +0000 (16:02 +0530)
Signed-off-by: SravanKumarGunda <sravan.kumar1@huawei.com>
Issue-ID: CLI-270
Change-Id: Iba00ddc8c471bc5990d87ba3729af373e2bd6711

29 files changed:
framework/src/main/java/org/onap/cli/fw/cmd/execution/OnapCommandExceutionListCommand.java
framework/src/main/java/org/onap/cli/fw/cmd/product/OnapProductsListCommand.java
framework/src/main/java/org/onap/cli/fw/output/OnapCommandResultAttribute.java
framework/src/main/java/org/onap/cli/fw/output/OnapCommandResultType.java
framework/src/main/java/org/onap/cli/fw/output/print/OnapCommandPrint.java
framework/src/main/java/org/onap/cli/fw/output/print/TableGenerator.java
framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaLoader.java
framework/src/main/java/org/onap/cli/fw/store/OnapCommandExecutionStore.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/cmd/sample/OnapCommandSampleTest.java
framework/src/test/java/org/onap/cli/fw/conf/OnapCommandConfgTest.java
framework/src/test/java/org/onap/cli/fw/schema/ValidateSchemaTest.java
framework/src/test/java/org/onap/cli/fw/utils/OnapCommandUtilsTest.java
framework/src/test/resources/schema-validate-basic-default-attr.yaml [new file with mode: 0644]
grpc/grpc-client/src/main/java/org/open/infc/grpc/client/OpenRemoteCli.java
grpc/grpc-server/src/main/java/org/open/infc/grpc/server/OpenInterfaceGrpcServer.java
main/src/test/java/org/onap/cli/main/OnapCommandSampleTest.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/conf/OnapCommandHttpConstants.java
profiles/http/src/main/java/org/onap/cli/fw/http/connect/OnapHttpConnection.java
profiles/http/src/main/java/org/onap/cli/fw/http/error/OnapCommandFailedMocoGenerate.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/utils/OnapCommandUtilsTest.java
validate/sample-mock-generator/src/main/java/org/onap/cli/http/mock/MockJsonGenerator.java

index 5470472..349fb52 100644 (file)
@@ -37,7 +37,7 @@ public class OnapCommandExceutionListCommand extends OnapCommand {
     protected void run() throws OnapCommandException {
 
         Map<String, String> map = new HashMap<>();
-        for (String input: Arrays.asList(new String []{"request-id", "product", "service", "command", "profile", "start-time", "end-time"})) {
+        for (String input: Arrays.asList("request-id", "product", "service", "command", "profile", "start-time", "end-time")) {
             String value = getParametersMap().get(input).getValue().toString();
             if (value != null && !value.isEmpty()) {
                 map.put(input, value);
index 10d9c44..42dc27e 100644 (file)
@@ -59,7 +59,7 @@ public class OnapProductsListCommand extends OnapCommand {
             if (stream != null) {
                 Map<String, ?> map = OnapCommandDiscoveryUtils.loadYaml(stream);
                 Map<String, String> productMap = (Map<String, String>) map.get("product");
-                String description = (String) productMap.get(OnapCommandConstants.DESCRIPTION);
+                String description = productMap.get(OnapCommandConstants.DESCRIPTION);
                 this.getResult().getRecordsMap().get("description").getValues().add(description.trim());
             } else {
                 this.getResult().getRecordsMap().get("description").getValues().add("");
index 76af42d..307e1b9 100644 (file)
@@ -94,7 +94,7 @@ public class OnapCommandResultAttribute {
 
     public List<String> getValues() {
         if (this.values.isEmpty() && !this.defaultValue.isEmpty()) {
-            return Arrays.asList(new String [] {this.defaultValue});
+            return Arrays.asList(this.defaultValue);
         }
         return values;
     }
index ebd13eb..a1029ca 100644 (file)
@@ -31,11 +31,7 @@ public enum OnapCommandResultType {
      * @return boolean
      */
     public static boolean isTabularForm(String type) {
-        if (type.equalsIgnoreCase(TABLE.name())) {
-            return true;
-        }
-
-        return false;
+        return type.equalsIgnoreCase(TABLE.name());
     }
 
     /**
index 8d70790..7a125ce 100644 (file)
@@ -238,7 +238,7 @@ public class OnapCommandPrint {
 
     public Object getJsonNodeOrString(String value) {
         try {
-            return (JSONObject) JSONValue.parse(value);
+            return JSONValue.parse(value);
         } catch (Exception e) {
             return value;
         }
index 8be7952..389a98f 100644 (file)
@@ -80,7 +80,7 @@ public class TableGenerator {
                     for (int cellIndex = 0; cellIndex < row.size(); cellIndex++) {
                         Object cell = row.get(cellIndex);
                         String finalCell = "";
-                        if (cell != null && cell instanceof List) {
+                        if (cell instanceof List) {
                             List<String> list = (List<String>) cell;
                             if (splitCellIndex < list.size()) {
                                 finalCell = list.get(splitCellIndex);
index 41be233..4f6e4ea 100644 (file)
@@ -346,11 +346,7 @@ public class OnapCommandSchemaLoader {
                                                     IS_OPTIONAL, String.valueOf(parameter.get(key2))));
                                         }
 
-                                        if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) {
-                                            param.setOptional(true);
-                                        } else {
-                                            param.setOptional(false);
-                                        }
+                                        param.setOptional(BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2))));
                                         break;
 
                                     case IS_SECURED:
@@ -361,11 +357,7 @@ public class OnapCommandSchemaLoader {
                                             }
                                         }
 
-                                        if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) {
-                                            param.setSecured(true);
-                                        } else {
-                                            param.setSecured(false);
-                                        }
+                                        param.setSecured(BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2))));
                                         break;
 
                                     case IS_INCLUDE:
@@ -374,11 +366,7 @@ public class OnapCommandSchemaLoader {
                                                     IS_INCLUDE, String.valueOf(parameter.get(key2))));
                                         }
 
-                                        if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) {
-                                            param.setInclude(true);
-                                        } else {
-                                            param.setInclude(false);
-                                        }
+                                        param.setInclude(BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2))));
                                         break;
 
                                     case IS_DEFAULT_PARAM:
@@ -389,11 +377,7 @@ public class OnapCommandSchemaLoader {
                                             }
                                         }
 
-                                        if (BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2)))) {
-                                            param.setDefaultParam(true);
-                                        } else {
-                                            param.setDefaultParam(false);
-                                        }
+                                        param.setDefaultParam(BOOLEAN_TRUE.equalsIgnoreCase(String.valueOf(parameter.get(key2))));
                                         break;
                                 }
                             }
@@ -477,11 +461,7 @@ public class OnapCommandSchemaLoader {
                                                                     IS_SECURED, String.valueOf(map.get(key4))));
                                                         }
                                                     }
-                                                    if (BOOLEAN_TRUE.equals(String.valueOf(map.get(key4)))) {
-                                                        attr.setSecured(true);
-                                                    } else {
-                                                        attr.setSecured(false);
-                                                    }
+                                                    attr.setSecured(BOOLEAN_TRUE.equals(String.valueOf(map.get(key4))));
                                                     break;
 
                                                 case IS_DEFAULT_ATTR:
@@ -491,11 +471,7 @@ public class OnapCommandSchemaLoader {
                                                                     IS_DEFAULT_ATTR, String.valueOf(map.get(key4))));
                                                         }
                                                     }
-                                                    if (BOOLEAN_TRUE.equals(String.valueOf(map.get(key4)))) {
-                                                        attr.setDefaultAttr(true);
-                                                    } else {
-                                                        attr.setDefaultAttr(false);
-                                                    }
+                                                    attr.setDefaultAttr(BOOLEAN_TRUE.equals(String.valueOf(map.get(key4))));
                                                     break;
                                             }
 
index 9e230ff..b0ebbda 100644 (file)
@@ -59,17 +59,17 @@ public class OnapCommandExecutionStore {
     private static String SEPARATOR = "__";
 
     private enum SearchMode {
-        find,
-        file //for developer mode
+        FIND,
+        FILE //for developer mode
 
 
     }
 
-    private static SearchMode SEARCH_MODE = SearchMode.file;
+    private static SearchMode SEARCH_MODE = SearchMode.FILE;
     static {
         String mode = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_EXECUTION_SEARCH_MODE);
-        if (mode.equalsIgnoreCase(SearchMode.find.name()))
-            SEARCH_MODE = SearchMode.find;
+        if (mode.equalsIgnoreCase(SearchMode.FIND.name()))
+            SEARCH_MODE = SearchMode.FIND;
     }
 
     public static class ExecutionStoreContext {
@@ -334,7 +334,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") || SEARCH_MODE.equals(SearchMode.FILE)) {
                 for (File f: new File(getBasePath()).listFiles()) {
                     if(search.containsKey(EXECUTIONID)) {
                         if (f.getName().startsWith(search.get(EXECUTIONID)))
@@ -379,7 +379,7 @@ public class OnapCommandExecutionStore {
                     searchString.append("*");
                 }
 
-                for (String term: Arrays.asList(new String []{"product", "service", "command", "profile"})) {
+                for (String term: Arrays.asList("product", "service", "command", "profile")) {
                     searchString.append("__");
                     if (search.get(term) != null && !search.get(term).isEmpty()) {
                         searchString.append(search.get(term));
@@ -453,8 +453,7 @@ public class OnapCommandExecutionStore {
 
             @Override
             public boolean accept(File dir, String name) {
-                if (name.startsWith(executionId)) return true;
-                return false;
+                return name.startsWith(executionId);
             }
         });
 
index 7a4dc49..0db9695 100644 (file)
@@ -57,8 +57,6 @@ import org.springframework.core.io.Resource;
 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
 import org.springframework.core.io.support.ResourcePatternResolver;
 import com.esotericsoftware.yamlbeans.YamlReader;
-import com.esotericsoftware.yamlbeans.YamlException;
-
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import com.google.gson.stream.JsonReader;
@@ -86,7 +84,7 @@ public class OnapCommandDiscoveryUtils {
     public static OnapCommandSchemaInfo getSchemaInfo(String cmd, String version) throws OnapCommandException {
         List<OnapCommandSchemaInfo> list = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(false);
         OnapCommandSchemaInfo schemaInfo = null;
-        if (list != null) {
+        if (list != null) { //NOSONAR
             for (OnapCommandSchemaInfo schema : list) {
                 if (cmd.equals(schema.getCmdName()) && version.equals(schema.getProduct())) {
                     schemaInfo = schema;
@@ -237,7 +235,7 @@ public class OnapCommandDiscoveryUtils {
      */
     public static Resource findResource(String fileName, String pattern) throws IOException {
         Resource[] resources = OnapCommandDiscoveryUtils.findResources(pattern);
-        if (resources != null && resources.length > 0) {
+        if (resources != null && resources.length > 0) { //NOSONAR
             for (Resource res : resources) {
                 if (res.getFilename().equals(fileName)) {
                     return res;
@@ -305,7 +303,7 @@ public class OnapCommandDiscoveryUtils {
                         //default_input_parameters_http.yaml
                         String profileName = resource.getFilename().substring(
                                 DEAFULT_INPUT_PARAMETERS_NAME.length() + 1,
-                                resource.getFilename().indexOf("."));
+                                resource.getFilename().indexOf('.'));
                         if (deafultResourceMap.containsKey(PARAMETERS)) {
                             List<Object> params = new ArrayList<>();
                             for (Map<String, ?> p: (List<Map<String, ?>>) deafultResourceMap.get(PARAMETERS)) {
@@ -491,7 +489,7 @@ public class OnapCommandDiscoveryUtils {
         OnapCommandSchemaInfo schemaInfo =  getSchemaInfo(cmd, version);
 
         List<String> sampleFiles = new ArrayList<>();
-        if (schemaInfo != null && !schemaInfo.getSampleFiles().isEmpty()) {
+        if (schemaInfo != null && !schemaInfo.getSampleFiles().isEmpty()) { //NOSONAR
             sampleFiles.addAll(schemaInfo.getSampleFiles());
         }
 
@@ -584,8 +582,6 @@ public class OnapCommandDiscoveryUtils {
         try(InputStreamReader inputStreamReader = new InputStreamReader(inputStream);){
             YamlReader reader = new YamlReader(inputStreamReader);
             values = (Map<String, ?>) reader.read();
-            } catch (YamlException e) {
-                throw new OnapCommandInvalidSchema(inputStream.getClass().getName(),e.getMessage());
             } catch (IOException e) {
                 throw new OnapCommandInvalidSchema(inputStream.getClass().getName(),e.getMessage());
             }
index 323e9e7..e115088 100644 (file)
@@ -183,7 +183,7 @@ public class OnapCommandHelperUtils {
             resultTable.getRecords().add(attrHelp);
         }
 
-        if (cmd.getResult().getRecords().size() > 0) {
+        if (!cmd.getResult().getRecords().isEmpty()) {
             try {
                 help.append("\n\nResults::\n\n" + resultTable.print());
             } catch (OnapCommandException e) {
index 814f513..ea8e648 100644 (file)
@@ -124,7 +124,7 @@ public class OnapCommandUtils {
             if (idxS == -1) {
                 break;
             }
-            int idxE = line.indexOf("}", idxS);
+            int idxE = line.indexOf('}', idxS);
             String paramName = line.substring(idxS + 2, idxE);
             paramNames.add(paramName.trim());
 
@@ -213,7 +213,7 @@ public class OnapCommandUtils {
                 resultLine.append(line.substring(currentIdx));
                 break;
             }
-            int idxE = line.indexOf("}", idxS);
+            int idxE = line.indexOf('}', idxS);
             String attr = line.substring(idxS + 3, idxE);
             attr = attr.trim();
 
@@ -246,7 +246,7 @@ public class OnapCommandUtils {
                 resultSpl.append(lineSpl.substring(currentIdx));
                 break;
             }
-            int idxE = lineSpl.indexOf("}", idxS);
+            int idxE = lineSpl.indexOf('}', idxS);
             String splEntry = lineSpl.substring(idxS + 3, idxE);
             splEntry = splEntry.trim();
 
@@ -319,7 +319,7 @@ public class OnapCommandUtils {
                 result.append(line.substring(currentIdx));
                 break;
             }
-            int idxE = line.indexOf("}", idxS);
+            int idxE = line.indexOf('}', idxS);
             String paramName = line.substring(idxS + 2, idxE);
             paramName = paramName.trim();
             if (!params.containsKey(paramName)) {
index bb37c47..69df607 100644 (file)
@@ -31,6 +31,7 @@ import java.util.concurrent.TimeUnit;
 import org.apache.commons.io.IOUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import java.nio.charset.StandardCharsets;
 
 public class ProcessRunner {
     private static Logger log = LoggerFactory.getLogger(ProcessRunner.class);
@@ -127,7 +128,7 @@ public class ProcessRunner {
             public void run() {
                 try {
                     IOUtils.copy(stdoutP, stdout);
-                } catch (IOException e) {
+                } catch (IOException e) { // NOSONAR
                 }
             }
         });
@@ -136,7 +137,7 @@ public class ProcessRunner {
             public void run() {
                 try {
                     IOUtils.copy(stderrP, stderr);
-                } catch (IOException e) {
+                } catch (IOException e) { // NOSONAR
                 }
             }
         });
@@ -153,10 +154,10 @@ public class ProcessRunner {
         }
 
         if (readOutput)
-            this.output = new String(((ByteArrayOutputStream)this.getStdout()).toByteArray(), "UTF-8");
+            this.output = new String(((ByteArrayOutputStream)this.getStdout()).toByteArray(), StandardCharsets.UTF_8);
 
         if (readError)
-            this.error = new String(((ByteArrayOutputStream)this.getStderr()).toByteArray(), "UTF-8");;
+            this.error = new String(((ByteArrayOutputStream)this.getStderr()).toByteArray(), StandardCharsets.UTF_8);
 
         p.destroy();
 
index 3e32f3e..60aa5e7 100644 (file)
@@ -114,7 +114,7 @@ public class OnapCommandSampleTest {
             UUID.fromString(attrValue.substring(4));
             attr = sample.getResult().getRecordsMap().get("output-2");
             attrValue = attr.getValues().get(0);
-            assertEquals(attrValue, "test");
+            assertEquals("test", attrValue);
         } catch (IllegalArgumentException e) {
             fail("Failed to replace the output default value on output-1");
         } catch (OnapCommandException e) {
index d6ef3a3..ae62063 100644 (file)
 
 package org.onap.cli.fw.conf;
 
+import org.junit.Test;
+
 public class OnapCommandConfgTest {
 
+       @Test
+       public void addPropertiesTest() {
+
+           OnapCommandConfig.getPropertyValue("cli.schema.profile.confs");
+       }
+
 }
index 5831c27..4c64ca2 100644 (file)
@@ -123,4 +123,18 @@ public class ValidateSchemaTest {
         assertTrue(errorList5.size() == 0);
 
     }
+
+    @Test
+    public void validateAfterRemovingIfElseTest() throws OnapCommandException {
+        OnapCommand cmd2 = new OnapCommand() {
+            @Override
+            protected void run() throws OnapCommandException {
+
+            }
+        };
+        List < String > errorList2 = OnapCommandSchemaLoader.loadSchema(cmd2,
+            "schema-validate-basic-default-attr.yaml", true, true);
+        assertTrue(errorList2.size() > 0);
+    }
+
 }
index e01c387..b7da1c2 100644 (file)
@@ -533,4 +533,15 @@ public class OnapCommandUtilsTest {
    public void testMd5(){
     assertNotNull(OnapCommandUtils.md5("a"));
     }
+
+   @Test
+   public void replaceLineFromResults() {
+          Map<String, String> mapExample = new HashMap<String, String>();
+          mapExample.put("key1", "paramA");
+          mapExample.put("key2", "paramB");
+          OnapCommandUtils.replaceLineFromResults("line $r{paramA} line $r{paramB}", mapExample);
+          assertTrue(mapExample.get("key1").equals("paramA"));
+          assertTrue(mapExample.get("key2").equals("paramB"));
+   }
+
 }
diff --git a/framework/src/test/resources/schema-validate-basic-default-attr.yaml b/framework/src/test/resources/schema-validate-basic-default-attr.yaml
new file mode 100644 (file)
index 0000000..03d0628
--- /dev/null
@@ -0,0 +1,91 @@
+# Copyright 2018 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.
+
+open_cli_schema_version: 1.0
+description: Register microservice into Onap
+name: schema-validate
+info:
+  product: open-cli
+  service: test
+  type: cmd
+  author: Sravan Kumar sravan.kumar1@huawei.com
+parameters:
+  - name: service-name1
+    description: Oclip service name
+    type: string
+    short_option: x
+    long_option: service-name
+    is_optional: false
+  - name: service-version
+    description: Oclip service version
+    type: string
+    short_option: y
+    long_option: service-version
+    is_optional: false
+  - name: service-url
+    description: Oclip service base url
+    type: url1
+    short_option: u
+    long_option: service-url
+    is_optional: false1
+  - name: status
+    description: Oclip service status
+    type: digit
+    short_option: z
+    long_option: service-version
+    is_optional: true
+    default_value: 1
+  - name: node-ip
+    description: Oclip service running node IP
+    type: string
+  - name: node-port
+    description: Oclip service running node port
+    type: string
+  - name: create-or-update
+    description: Oclip service create or update
+    type: cfbcv
+    default_value: true
+results:
+  direction: portrait1
+  attributes:
+    - name: name
+      description: Oclip service name
+      scope: short
+      type: string
+      is_default_attr: true
+    - name: version
+      description: Oclip service version
+      scope: short
+      type: string
+      is_default_attr: true
+    - name: status
+      description: Oclip service base url
+      scope: short
+      type: url
+      is_default_attr: true
+    - name: status
+      description: Oclip service status
+      scope: short1
+      type: digit
+      is_default_attr: true
+    - name: nodes
+      description: Oclip service running nodes
+      scope: long
+      type: string
+      is_default_attr: true
+    - name: location
+      description: Oclip service location
+      scope: long
+      type: url
+      is_default_attr: true
\ No newline at end of file
index 724267e..1875a76 100644 (file)
@@ -44,8 +44,7 @@ public class OpenRemoteCli {
         OpenInterfaceGrpcClient client = new OpenInterfaceGrpcClient(
                 host, port, timeout);
         try {
-            Result result = client.remoteCli(Args.newBuilder().setRequestId(this.requestId).addAllArgs(args).build());
-            return result;
+            return client.remoteCli(Args.newBuilder().setRequestId(this.requestId).addAllArgs(args).build());
         } finally {
           client.shutdown();
         }
@@ -63,8 +62,7 @@ public class OpenRemoteCli {
             params.put("format", "json");
             Input input = Input.newBuilder().setAction(action).setRequestId(requestId).putAllOptions(options).putAllParams(params).build();
 
-            Output output = client.invoke(input);
-            return output;
+            return client.invoke(input);
         } finally {
           client.shutdown();
         }
@@ -86,8 +84,7 @@ public class OpenRemoteCli {
                   host, port);
 
           try {
-              Result result = client.remoteCli(Args.newBuilder().setRequestId(reqId).addAllArgs(args).build());
-              return result;
+              return client.remoteCli(Args.newBuilder().setRequestId(reqId).addAllArgs(args).build());
           } finally {
             client.shutdown();
           }
@@ -117,8 +114,7 @@ public class OpenRemoteCli {
             params.put("format", "json");
             Input input = Input.newBuilder().setAction(action).setRequestId(reqId).putAllOptions(options).putAllParams(params).build();
 
-            Output output = client.invoke(input);
-            return output;
+            return client.invoke(input);
         } finally {
           client.shutdown();
         }
index 9f236e5..6bca7b3 100644 (file)
@@ -126,6 +126,7 @@ public class OpenInterfaceGrpcServer {
 
         private String outputs = "";
 
+          @Override
           public void print(String msg) {
               outputs += msg + "\n";
           }
index 3ec63ae..bf61d34 100644 (file)
@@ -19,6 +19,12 @@ package org.onap.cli.main;
 import org.onap.cli.fw.cmd.OnapCommand;
 import org.onap.cli.fw.error.OnapCommandException;
 import org.onap.cli.fw.schema.OnapCommandSchema;
+import org.onap.cli.fw.input.OnapCommandParameter;
+import org.onap.cli.fw.registrar.OnapCommandRegistrar;
+import java.util.HashSet;
+import java.util.Set;
+import org.junit.Test;
+import org.onap.cli.fw.conf.OnapCommandConstants;
 
 /**
  * This command helps to test the Command functionalities.
@@ -32,4 +38,22 @@ public class OnapCommandSampleTest extends OnapCommand {
 
     }
 
+    @Test
+    public void sampleTestVersion() throws OnapCommandException {
+
+        Set < OnapCommandParameter > parameters = new HashSet < > ();
+        OnapCommandParameter version = new OnapCommandParameter();
+        version.setName(OnapCommandConstants.DEFAULT_PARAMETER_VERSION);
+        version.setValue(true);
+        parameters.add(version);
+        OnapCommandParameter hlp = new OnapCommandParameter();
+        hlp.setName(OnapCommandConstants.DEFAULT_PARAMETER_HELP);
+        hlp.setValue(false);
+        parameters.add(hlp);
+
+        OnapCommand sample = OnapCommandRegistrar.getRegistrar().get("sample-test");
+        sample.setParameters(parameters);
+        sample.execute();
+    }
+
 }
index eb7b808..dd2c26c 100644 (file)
@@ -22,7 +22,6 @@ import java.io.FileOutputStream;
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
@@ -46,12 +45,10 @@ import org.onap.cli.fw.store.OnapCommandExecutionStore;
 import org.onap.cli.fw.utils.OnapCommandUtils;
 import org.onap.cli.fw.utils.ProcessRunner;
 
-import com.google.gson.Gson;
 import com.jayway.jsonpath.JsonPath;
 import com.jayway.jsonpath.PathNotFoundException;
 
 import net.minidev.json.JSONArray;
-import net.minidev.json.JSONObject;
 
 /**
  * Hello world.
@@ -191,7 +188,7 @@ public class OpenCommandShellCmd extends OnapCommand {
 
         ProcessRunner pr = new ProcessRunner(
                 cmd,
-                (envs.size() > 0) ? envs.toArray(new String []{}) : null,
+                (!envs.isEmpty()) ? envs.toArray(new String []{}) : null,
                 cwd);
         FileOutputStream stdoutStream = null;
         FileOutputStream stderrStream = null;
@@ -285,11 +282,7 @@ public class OpenCommandShellCmd extends OnapCommand {
             }
 
         //check for pass/failure
-        if (!this.passCodes.isEmpty() && !this.passCodes.contains(pr.getExitCode())) {
-            this.getResult().setPassed(false);
-        } else {
-            this.getResult().setPassed(true);
-        }
+        this.getResult().setPassed(!(!this.passCodes.isEmpty() && !this.passCodes.contains(pr.getExitCode())));
    }
 
     public String getOutput() {
@@ -315,10 +308,10 @@ public class OpenCommandShellCmd extends OnapCommand {
                 break;
             }
 
-            int idxE = line.indexOf("}", idxS);
+            int idxE = line.indexOf('}', idxS);
             String tmpName = line.substring(idxS + 7, idxE);
             tmpName = tmpName.trim();
-            String tmpTkns[] = tmpName.split(":");
+            String[] tmpTkns = tmpName.split(":");
             String tmpFileName;
             String paramName;
             if (tmpTkns.length == 2) {
@@ -382,7 +375,7 @@ public class OpenCommandShellCmd extends OnapCommand {
                     break;
                 }
             }
-            int idxE = line.indexOf("}", idxS);
+            int idxE = line.indexOf('}', idxS);
             String jsonPath = line.substring(idxS + 3, idxE);
             jsonPath = jsonPath.trim();
             Object value = new Object();
index 676aeb3..1eeadec 100644 (file)
@@ -26,6 +26,7 @@ import org.onap.cli.fw.cmd.conf.OnapCommandCmdConstants;
 import org.onap.cli.fw.conf.OnapCommandConfig;
 import org.onap.cli.fw.error.OnapCommandException;
 import org.onap.cli.fw.utils.OnapCommandUtils;
+import java.util.stream.Collectors;
 
 public class OnapCommandSchemaCmdLoader {
 
@@ -64,7 +65,7 @@ public class OnapCommandSchemaCmdLoader {
                         if (o instanceof List) {
                             cmd.setCommand((List<String>) o);
                         } else {
-                            cmd.setCommand(Arrays.asList(new String [] {(String) o}));
+                            cmd.setCommand(Arrays.asList((String) o));
                         }
                         break;
 
@@ -90,7 +91,8 @@ public class OnapCommandSchemaCmdLoader {
                         break;
 
                     case OnapCommandCmdConstants.SUCCESS_EXIT_CODE:
-                        cmd.setSuccessStatusCodes((ArrayList) valMap.get(key1));
+                        List<String> list = (ArrayList) valMap.get(key1);
+                        cmd.setSuccessStatusCodes(list.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList()));
                         break;
 
                     case OnapCommandCmdConstants.PASS_CODE:
index 6a87ed1..7ab7928 100644 (file)
@@ -94,7 +94,7 @@ public class OnapCommandHttpConstants {
     //context param
     public static final String CONTEXT = "context";
     public static final String CONTEXT_REMOVE_EMPTY_JSON_NODES = "remove_empty_node";
-    public static final String __BODY__ = "__body__";
+    public static final String __BODY__ = "__body__"; //NOSONAR
 
     // moco server const
     public static final String VERIFY_MOCO_HOST = "cli.verify.host";
index 3533e92..732e6c0 100644 (file)
@@ -365,11 +365,10 @@ public class OnapHttpConnection {
         } else {
             String fileTag = (!input.getMultipartEntityName().isEmpty()) ? input.getMultipartEntityName() : "file";
             File file = new File(input.getBody().trim());
-            HttpEntity multipartEntity = MultipartEntityBuilder
+            return MultipartEntityBuilder
                     .create()
                     .addBinaryBody(fileTag, file, ContentType.create("application/octet-stream"), file.getName())
                     .build();
-            return multipartEntity;
         }
     }
 
index 33f5806..d064547 100644 (file)
@@ -138,8 +138,8 @@ public class OnapCommandSchemaHttpLoader {
                                                 for (Object part: multiparts ) {
                                                     HttpInput.Part partO = new HttpInput.Part();
                                                     Map<String, String> partMap = (Map<String, String>) part;
-                                                    partO.setName((String) partMap.get("name"));
-                                                    partO.setContent((String)partMap.get("content"));
+                                                    partO.setName(partMap.get("name"));
+                                                    partO.setContent(partMap.get("content"));
                                                     if (partMap.get("type") != null && ((String)partMap.get("type")).equalsIgnoreCase("file")) {
                                                         partO.setBinary(true);
                                                     }
index fcd25c2..ec2f572 100644 (file)
@@ -93,7 +93,7 @@ public class OnapCommandHttpUtils {
             values.put(param.getKey(), param.getValue().getValue().toString());
         }
 
-        if (input.getMultiparts().size() > 0) {
+        if (!input.getMultiparts().isEmpty()) {
             for (HttpInput.Part part: input.getMultiparts()) {
                 part.setContent(OnapCommandUtils.replaceLineForSpecialValues(part.getContent(), values));
                 part.setContent(OnapCommandUtils.replaceLineFromInputParameters(part.getContent(), params));
@@ -190,7 +190,7 @@ public class OnapCommandHttpUtils {
                 headerProcessedLine.append(line.substring(currentIdx));
                 break;
             }
-            int idxE = line.indexOf("}", idxS);
+            int idxE = line.indexOf('}', idxS);
             String headerName = line.substring(idxS + 3, idxE);
             headerName = headerName.trim();
             if (!resultHttp.getRespHeaders().containsKey(headerName)) {
index 37fc846..6807321 100644 (file)
@@ -53,6 +53,8 @@ import java.util.List;
 import org.onap.cli.fw.error.OnapCommandResultMapProcessingFailed;
 import org.onap.cli.fw.error.OnapCommandResultEmpty;
 import static org.junit.Assert.assertFalse;
+import org.onap.cli.fw.http.connect.HttpInput;
+import org.onap.cli.fw.http.connect.HttpInput.Part;
 
 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
 public class OnapCommandUtilsTest {
@@ -205,4 +207,22 @@ public class OnapCommandUtilsTest {
                 + "[\"3a2fb75b52a54e9c8093e7c154210f9e\"]}]}}}";
         assertEquals(result, OnapCommandHttpUtils.normalizeJson(sample));
     }
+
+    @Test
+    public void testPopulateParameters() throws OnapCommandException {
+        List <Part> multiparts = new ArrayList <HttpInput.Part> ();
+        Part part = new Part();
+        part.setContent("content");
+        multiparts.add(part);
+        Map <String, OnapCommandParameter> params = new HashMap <String, OnapCommandParameter> ();
+        OnapCommandParameter onapCommandParameter = new OnapCommandParameter();
+        onapCommandParameter.setName("CMD");
+        onapCommandParameter.setRawDefaultValue("value");
+        params.put("key", onapCommandParameter);
+        HttpInput httpInput = new HttpInput();
+        httpInput.setMultiparts(multiparts);
+        HttpInput input = OnapCommandHttpUtils.populateParameters(params, httpInput);
+        assertTrue(input != null);
+    }
+
 }