Code improvement for pending sonar issues 00/110400/7
authorjitendra007 <jitendra.sharma1@huawei.com>
Tue, 21 Jul 2020 09:05:31 +0000 (14:35 +0530)
committerpriyanka.akhade <priyanka.akhade@huawei.com>
Tue, 4 Aug 2020 04:14:38 +0000 (09:44 +0530)
Issue-ID: CLI-270

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

16 files changed:
framework/src/main/java/org/onap/cli/fw/cmd/product/OnapServiceListCommand.java
framework/src/main/java/org/onap/cli/fw/schema/OnapCommandSchemaMerger.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/OnapCommandUtils.java
grpc/grpc-client/src/main/java/org/open/infc/grpc/client/OpenInterfaceGrpcClient.java
grpc/grpc-server/src/main/java/org/open/infc/grpc/server/OpenInterfaceGrpcServer.java
main/src/main/java/org/onap/cli/main/OnapCli.java
profiles/command/src/main/java/org/onap/cli/fw/cmd/schema/OnapCommandSchemaCmdLoader.java
profiles/http/src/main/java/org/onap/cli/fw/http/auth/OnapCommandHttpAuthClient.java
profiles/http/src/main/java/org/onap/cli/fw/http/connect/OnapHttpConnection.java
profiles/http/src/main/java/org/onap/cli/fw/http/schema/OnapCommandSchemaHttpLoader.java
profiles/http/src/test/java/org/onap/cli/fw/http/OnapHttpConnectionTest.java
profiles/http/src/test/java/org/onap/cli/fw/http/error/OnapCommandErrorTest.java
profiles/snmp/src/main/java/org/onap/cli/fw/snmp/cmd/OnapSnmpCommand.java
validate/sample-yaml-generator/src/main/java/org/onap/cli/sample/yaml/SampleYamlGenerator.java

index 880f83e..36c701c 100644 (file)
@@ -51,7 +51,7 @@ public class OnapServiceListCommand extends OnapCommand {
             }
 
             if (!rslt.containsKey(schema.getProduct())) {
-                rslt.put(schema.getProduct(), new HashSet<String>());
+                rslt.put(schema.getProduct(), new HashSet<>());
             }
             rslt.get(schema.getProduct()).add(schema.getService());
         }
@@ -71,7 +71,7 @@ public class OnapServiceListCommand extends OnapCommand {
             }
         }
 
-        for (String service : rslt.getOrDefault(product, new HashSet<String>())) {
+        for (String service : rslt.getOrDefault(product, new HashSet<>())) {
             this.getResult().getRecordsMap().get("product").getValues().add(product);
             this.getResult().getRecordsMap().get("service").getValues().add(service);
             this.getResult().getRecordsMap().get("description").getValues().add(
index c2ae189..9a6a4e7 100644 (file)
@@ -33,13 +33,13 @@ import org.slf4j.LoggerFactory;
  */
 public class OnapCommandSchemaMerger {
 
-    static Logger LOG = LoggerFactory.getLogger(OnapCommandSchemaMerger.class);
+    static Logger logger = LoggerFactory.getLogger(OnapCommandSchemaMerger.class);
 
-    public static Map<String, ?> mergeSchemas(OnapCommand cmd) throws OnapCommandException {
-        Map<String, Object> mergedResult = new LinkedHashMap<String, Object>();
+    public static Map<String, Object> mergeSchemas(OnapCommand cmd) throws OnapCommandException {
+        Map<String, Object> mergedResult = new LinkedHashMap<>();
 
         for (String schema: cmd.getSchemas()) {
-            Map<String , Object> schemaMap = (Map<String, Object>) OnapCommandSchemaLoader.validateSchemaVersion(schema, cmd.getSchemaVersion());
+            Map<String , Object> schemaMap = OnapCommandSchemaLoader.validateSchemaVersion(schema, cmd.getSchemaVersion());
             mergeYamlMap(mergedResult, schemaMap);
         }
 
index 7352ece..839d142 100644 (file)
@@ -41,20 +41,20 @@ import org.slf4j.LoggerFactory;
 public class OnapCommandExecutionStore {
     private static Logger log = LoggerFactory.getLogger(OnapCommandExecutionStore.class);
 
-    private static boolean storeReady = false;
-    private static String REQUEST_ID = "requestId";
-    private static String EXECUTION_ID = "executionId";
-    private static String INPUT = "input";
-    private static String STDOUT = "stdout";
-    private static String STDERR = "stderr";
-    private static String DEBUG = "debug";
-    private static String IN_PROGRESS = "in-progress";
-    private static String OUTPUT = "output";
-    private static String ERROR = "error";
-    private static String COMPLETED = "completed";
-    private static String FAILED = "failed";
-    private static String EXECUTIONID = "execution-id";
-    private static String REQUESTID = "request-id";
+    private static boolean storeReady = false; // NOSONAR
+    private static final String REQUEST_ID = "requestId";
+    private static final String EXECUTION_ID = "executionId";
+    private static final String INPUT = "input";
+    private static final String STDOUT = "stdout";
+    private static final String STDERR = "stderr";
+    private static final String DEBUG = "debug";
+    private static final String IN_PROGRESS = "in-progress";
+    private static final String OUTPUT = "output";
+    private static final String ERROR = "error";
+    private static final String COMPLETED = "completed";
+    private static final String FAILED = "failed";
+    private static final String EXECUTIONID = "execution-id";
+    private static final String REQUESTID = "request-id";
 
     private SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
 
index 3964512..732ad00 100644 (file)
@@ -88,7 +88,7 @@ public class OnapCommandProfileStore {
     public void add(String productVersion, String paramName, String paramValue) {
 
         if (!paramCache.containsKey(productVersion)) {
-            paramCache.put(productVersion, new HashMap<String, String>());
+            paramCache.put(productVersion, new HashMap<>());
         }
 
         paramCache.get(productVersion).put(paramName, paramValue);
index 58fe7df..dab6669 100644 (file)
@@ -190,7 +190,7 @@ public class OnapCommandUtils {
      * @return
      */
     public static String replaceLineForSpecialValues(String lineSpl) {
-        return replaceLineForSpecialValues(lineSpl, new HashMap<String, String>());
+        return replaceLineForSpecialValues(lineSpl, new HashMap<>());
     }
 
     /**
@@ -410,7 +410,7 @@ public class OnapCommandUtils {
     }
 
     public static void copyParamsFrom(OnapCommand from, OnapCommand to) throws OnapCommandInvalidParameterValue {
-        copyParamsFrom(from, to, new HashMap<String, String>());
+        copyParamsFrom(from, to, new HashMap<>());
     }
 
     /**
index efc941f..fc007a0 100644 (file)
@@ -43,8 +43,7 @@ public class OpenInterfaceGrpcClient {
       public static class OpenInterfaceGrpcExecption extends Exception {
           private static final long serialVersionUID = -8755636432217894246L;
 
-          private int errorCode = -1;
-
+          private int errorCode = -1; //NOSONAR
           public OpenInterfaceGrpcExecption(int errorCode, String message) {
               super(message);
               this.errorCode = errorCode;
@@ -52,10 +51,10 @@ public class OpenInterfaceGrpcClient {
       }
 
       public static class OpenInterfaceGrpcTimeoutExecption extends OpenInterfaceGrpcExecption {
-          private static int errorCode = 1;
+          private static final int ERROR_CODE = 1;
 
           public OpenInterfaceGrpcTimeoutExecption(String message) {
-              super(errorCode, message);
+              super(ERROR_CODE, message);
           }
       }
 
index a7c0b17..c2a6132 100644 (file)
@@ -159,8 +159,8 @@ public class OpenInterfaceGrpcServer {
                         //Set the profile to current one
                         OnapCommandRegistrar.getRegistrar().setProfile(
                                 profile,
-                                new ArrayList<String>(),
-                                new ArrayList<String>());
+                                new ArrayList<>(),
+                                new ArrayList<>());
 
                         //fill from profile
                         Map<String, String> cache= OnapCommandRegistrar.getRegistrar().getParamCache(product);
index 061c1f7..1c27205 100644 (file)
@@ -225,8 +225,8 @@ public class OnapCli {
             if (this.profile != null) {
                 OnapCommandRegistrar.getRegistrar().setProfile(
                         this.profile,
-                        new ArrayList<String>(),
-                        new ArrayList<String>());
+                        new ArrayList<>(),
+                        new ArrayList<>());
             }
         } catch (Exception e) {
             this.print(e);
@@ -378,10 +378,9 @@ public class OnapCli {
                         break;
                     } else if (OnapCliConstants.PARAM_INTERACTIVE_CLEAR.equalsIgnoreCase(line)) {
                         console.clearScreen();
-                        continue;
-                    }
-                    this.args = new ArrayList<>();
-                    this.args.addAll(Arrays.asList(line.split(OnapCliConstants.PARAM_INTERACTIVE_ARG_SPLIT_PATTERN)));
+                    } else {
+                        this.args = new ArrayList<>();
+                        this.args.addAll(Arrays.asList(line.split(OnapCliConstants.PARAM_INTERACTIVE_ARG_SPLIT_PATTERN)));
 
                     if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_USE)) {
                         if (args.size() == 1) {
@@ -397,53 +396,46 @@ public class OnapCli {
                         }
 
                     } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_HELP)) {
-                        try {
-                            this.print(OnapCommandRegistrar.getRegistrar().getHelpForEnabledProductVersion());
-                            this.print(OnapCli.getDirectiveHelp());
-                        } catch (OnapCommandException e) {
-                            this.print(e);
-                        }
-
-                    } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_VERSION)) {
-                        this.printVersion = true;
-                        handleVersion();
-
-                    } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_PROFILE)) {
-                        if (args.size() == 1) {
-                            this.print("Please use it in the form of 'profile <profile-name>'\n");
-                            this.print("Available profiles: ");
-                            this.print(OnapCommandRegistrar.getRegistrar().getUserProfiles().toString());
-                        } else {
-                            this.profile = args.get(1);
-                            handleProfile();
-                        }
+                        this.print(OnapCommandRegistrar.getRegistrar().getHelpForEnabledProductVersion());
+                        this.print(OnapCli.getDirectiveHelp());
+                        } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_VERSION)) {
+                            this.printVersion = true;
+                            handleVersion();
+
+                        } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_PROFILE)) {
+                            if (args.size() == 1) {
+                                this.print("Please use it in the form of 'profile <profile-name>'\n");
+                                this.print("Available profiles: ");
+                                this.print(OnapCommandRegistrar.getRegistrar().getUserProfiles().toString());
+                            } else {
+                                this.profile = args.get(1);
+                                handleProfile();
+                            }
 
-                    } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_SET)) {
-                        if (args.size() > 1) {
-                            String [] paramEntry = args.get(1).trim().split("=", 2);
-                            if (paramEntry.length == 2) {
-                                OnapCommandRegistrar.getRegistrar().addParamCache(paramEntry[0].trim(), paramEntry[1].trim());
+                        } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_SET)) {
+                            if (args.size() > 1) {
+                                String[] paramEntry = args.get(1).trim().split("=", 2);
+                                if (paramEntry.length == 2) {
+                                    OnapCommandRegistrar.getRegistrar().addParamCache(paramEntry[0].trim(), paramEntry[1].trim());
+                                } else {
+                                    this.print("Please use it in the form of 'set <param-name>=<param-value>'");
+                                }
                             } else {
-                                this.print("Please use it in the form of 'set <param-name>=<param-value>'");
+                                this.print(OnapCommandRegistrar.getRegistrar().getParamCache().toString());
                             }
-                        } else {
-                            this.print(OnapCommandRegistrar.getRegistrar().getParamCache().toString());
-                        }
 
-                    } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_UNSET)) {
-                        if (args.size() > 1) {
-                            for (int i = 1; i <args.size(); i++) {
-                                OnapCommandRegistrar.getRegistrar().removeParamCache(args.get(i));
+                        } else if (!args.isEmpty() && this.args.get(0).equals(OnapCliConstants.PARAM_INTERACTIVE_UNSET)) {
+                            if (args.size() > 1) {
+                                for (int i = 1; i < args.size(); i++) {
+                                    OnapCommandRegistrar.getRegistrar().removeParamCache(args.get(i));
+                                }
+                            }
+                        } else {
+                            if (!(args.size() == 1 && args.get(0).trim().isEmpty())) {
+                                this.setArgs(this.args.toArray(new String[]{}));
+                                handleCommand();
                             }
                         }
-                    } else {
-                        if (args.size() == 1 && args.get(0).trim().isEmpty()) {
-                            //Ignore blanks // NOSONAR
-                            continue;
-                        }
-
-                        this.setArgs(this.args.toArray(new String [] {}));
-                        handleCommand();
                     }
                 }
             } catch (IOException e) { // NOSONAR
index 2d40806..8c2c4eb 100644 (file)
@@ -92,7 +92,7 @@ public class OnapCommandSchemaCmdLoader {
 
                     case OnapCommandCmdConstants.SUCCESS_EXIT_CODE:
                         List<String> list = (ArrayList) valMap.get(key1);
-                        cmd.setSuccessStatusCodes(list.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList()));
+                        cmd.setSuccessStatusCodes(list.stream().map(Integer::parseInt).collect(Collectors.toList()));
                         break;
 
                     case OnapCommandCmdConstants.PASS_CODE:
index e5f17be..075c130 100644 (file)
@@ -32,6 +32,10 @@ import org.onap.cli.fw.http.schema.OnapCommandSchemaHttpLoader;
 import org.onap.cli.fw.output.OnapCommandResultAttribute;
 import org.onap.cli.fw.registrar.OnapCommandRegistrar;
 import org.onap.cli.fw.utils.OnapCommandUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import java.io.IOException;
+import org.onap.cli.fw.http.error.OnapCommandLoginFailed;
 
 /**
  * Oclip Auth client helps to do login and logout.
@@ -39,6 +43,7 @@ import org.onap.cli.fw.utils.OnapCommandUtils;
  */
 public class OnapCommandHttpAuthClient {
 
+    private static Logger logger = LoggerFactory.getLogger(OnapCommandHttpAuthClient.class); //NOSONAR
     private OnapHttpCommand cmd = null;
 
     private OnapHttpConnection http = null;
@@ -98,7 +103,11 @@ public class OnapCommandHttpAuthClient {
 
         logout.execute();
 
-        this.http.close();
+        try {
+            this.http.close();
+        } catch (IOException e) {
+            throw new OnapCommandLoginFailed("Exception when closing httpclient");
+        }
     }
 
     /**
index 732e6c0..95ad726 100644 (file)
@@ -38,7 +38,6 @@ import org.apache.http.HttpResponse;
 import org.apache.http.annotation.Contract;
 import org.apache.http.annotation.ThreadingBehavior;
 import org.apache.http.client.CookieStore;
-import org.apache.http.client.HttpClient;
 import org.apache.http.client.config.RequestConfig;
 import org.apache.http.client.methods.HttpDelete;
 import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
@@ -47,14 +46,11 @@ import org.apache.http.client.methods.HttpPatch;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.client.methods.HttpPut;
 import org.apache.http.client.methods.HttpRequestBase;
-import org.apache.http.client.protocol.ClientContext;
 import org.apache.http.config.Registry;
 import org.apache.http.config.RegistryBuilder;
 import org.apache.http.conn.HttpClientConnectionManager;
 import org.apache.http.conn.socket.ConnectionSocketFactory;
-import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
-import org.apache.http.conn.ssl.X509HostnameVerifier;
 import org.apache.http.cookie.Cookie;
 import org.apache.http.entity.ContentType;
 import org.apache.http.entity.StringEntity;
@@ -71,7 +67,10 @@ import org.onap.cli.fw.http.conf.OnapCommandHttpConstants;
 import org.onap.cli.fw.http.error.OnapCommandHttpFailure;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.impl.client.CloseableHttpClient;
+import javax.net.ssl.HostnameVerifier;
 /**
  * Helps to make http connection.<br>
  */
@@ -79,7 +78,7 @@ public class OnapHttpConnection {
 
     private static Logger log = LoggerFactory.getLogger(OnapHttpConnection.class);
 
-    private HttpClient httpClient = null;
+    private CloseableHttpClient httpClient = null;
 
     Map<String, String> mapCommonHeaders = new HashMap<> ();
 
@@ -108,7 +107,7 @@ public class OnapHttpConnection {
                     SSLContext sslContext = SSLContext.getInstance(OnapCommandHttpConstants.SSLCONTEST_TLS);
                     sslContext.init(null, new TrustManager[] { new TrustAllX509TrustManager() },
                             new java.security.SecureRandom());
-                    X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();
+                    HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
                     Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                             .<ConnectionSocketFactory>create()
                             .register("https", new SSLConnectionSocketFactory(sslContext, hostnameVerifier)).build();
@@ -320,7 +319,7 @@ public class OnapHttpConnection {
             CookieStore cookieStore = new BasicCookieStore();
             updateInputFromCookies(input, cookieStore);
             HttpContext localContext = new BasicHttpContext();
-            localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
+            localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
 
             this.initHttpClient(input.getUri().startsWith("https"));
 
@@ -337,11 +336,10 @@ public class OnapHttpConnection {
         return result;
     }
 
-    @SuppressWarnings("deprecation")
-    public void close() {
+    public void close() throws IOException {
         this.mapCommonHeaders.clear();
         if (this.httpClient != null) {
-            this.httpClient.getConnectionManager().shutdown();
+            this.httpClient.close();
         }
     }
 
index e7a643a..3550120 100644 (file)
@@ -246,7 +246,7 @@ public class OnapCommandSchemaHttpLoader {
                                 validateHttpSccessCodes(errorList, (List<Object>) valMap.get(key1));
                             }
                             List<String> list = (ArrayList) valMap.get(key1);
-                            cmd.setSuccessStatusCodes(list.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList()));
+                            cmd.setSuccessStatusCodes(list.stream().map(Integer::parseInt).collect(Collectors.toList()));
                             break;
 
                         case OnapCommandHttpConstants.RESULT_MAP:
index 2860388..68995db 100644 (file)
@@ -216,7 +216,7 @@ public class OnapHttpConnectionTest {
     }
 
     @Test()
-    public void httpUnSecuredCloseExceptionTest() throws OnapCommandHttpFailure {
+    public void httpUnSecuredCloseExceptionTest() throws IOException {
         inp.setMethod("other");
         con = new OnapHttpConnection();
         con.close();
index cd2131e..e007af1 100644 (file)
@@ -51,6 +51,13 @@ public class OnapCommandErrorTest {
         assertEquals("203::0x3001::Failed", failed.getMessage());
     }
 
+    @Test
+    public void oclipCommandLoginFailedTest3() {
+        OnapCommandLoginFailed failed = new OnapCommandLoginFailed("Failed");
+
+        assertEquals("0x4001::Login failed, Failed", failed.getMessage());
+    }
+
     @Test
     public void oclipCommandLoginFailedTest1() {
         OnapCommandLoginFailed failed = new OnapCommandLoginFailed(new Exception("Failed"));
index 4fc4753..08837a0 100644 (file)
@@ -41,7 +41,6 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
-import java.util.Vector;
 
 /**
  * Oclip snmp Command.
@@ -120,7 +119,7 @@ public class OnapSnmpCommand extends OnapCommand {
                     ResponseEvent responseEvent = snmp.send(getPDU(PDU.GET, oidStrArr), getTarget(), null);
                     if ( responseEvent != null) {
                         if (responseEvent.getResponse().getErrorStatus() == PDU.noError) {
-                            Vector<? extends VariableBinding> variableBindings = responseEvent.
+                            List<? extends VariableBinding> variableBindings = responseEvent.
                                     getResponse().getVariableBindings();
                             variableBindings.stream().forEach(varBinding -> { //NOSONAR
                                 String key = getKeyForValue(varBinding.getOid().toString());
index 3436a50..7e20fc8 100644 (file)
@@ -67,7 +67,7 @@ public class SampleYamlGenerator {
     }
 
     private static String printTabs() {
-        StringBuffer spaces = new StringBuffer();
+        StringBuilder spaces = new StringBuilder();
         for (int i=0; i < nTab; i++) {
             spaces.append("  ");
         }