Fix sonar Security Hotspots 53/124753/10
authorLiard Samuel <samuel.liard@orange.com>
Fri, 8 Oct 2021 07:21:18 +0000 (09:21 +0200)
committerhighstreetherbert <herbert.eiselt@highstreet-technologies.com>
Fri, 19 Nov 2021 10:25:38 +0000 (11:25 +0100)
Issue-ID: CCSDK-3491
Signed-off-by: sliard <samuel.liard@gmail.com>
Change-Id: I33787ccca2a8acd8085db6b2a915e8f2ac2511ec
Signed-off-by: Dan Timoney <dtimoney@att.com>
Signed-off-by: highstreetherbert <herbert.eiselt@highstreet-technologies.com>
lib/doorman/src/main/java/org/onap/ccsdk/features/lib/doorman/dao/MessageDaoImpl.java
lib/doorman/src/main/java/org/onap/ccsdk/features/lib/doorman/impl/MessageInterceptorImpl.java
lib/doorman/src/test/java/org/onap/ccsdk/features/lib/doorman/it/MessageQueueTest.java
lib/network-prioritization/src/main/java/org/onap/ccsdk/features/lib/npm/api/NpmServiceManagerImpl.java
lib/network-prioritization/src/main/java/org/onap/ccsdk/features/lib/npm/utils/NpmUtils.java
lib/rlock/src/main/java/org/onap/ccsdk/features/lib/rlock/LockHelperImpl.java
lib/rlock/src/main/java/org/onap/ccsdk/features/lib/rlock/SynchronizedFunction.java
lib/rlock/src/test/java/org/onap/ccsdk/features/lib/rlock/TestLockHelper.java
sdnr/northbound/addCMHandle/provider/src/main/java/org/onap/ccsdk/features/sdnr/northbound/addCMHandle/AddCMHandleProvider.java
sdnr/northbound/energysavings/provider/src/main/java/org/onap/ccsdk/features/sdnr/northbound/energysavings/EnergysavingsProvider.java

index f04ea62..e9a9ed6 100644 (file)
@@ -66,19 +66,33 @@ public class MessageDaoImpl implements MessageDao {
 
     @Override
     public void updateMessageStarted(long messageId, Date timestamp) {
-        updateMessageStatus("started_timestamp", messageId, null, timestamp);
+        // duplicate code with updateMessageCompleted to avoid SQL injection issue for sonar
+        try (Connection con = dataSource.getConnection()) {
+            try {
+                con.setAutoCommit(false);
+                String sql = "UPDATE message SET started_timestamp = ? WHERE message_id = ?";
+                try (PreparedStatement ps = con.prepareStatement(sql)) {
+                    ps.setTimestamp(1, new Timestamp(timestamp.getTime()));
+                    ps.setLong(2, messageId);
+                    ps.executeUpdate();
+                }
+                con.commit();
+            } catch (SQLException ex) {
+                con.rollback();
+                throw ex;
+            }
+        } catch (SQLException e) {
+            throw new RuntimeException("Error updating message status in DB: " + e.getMessage(), e);
+        }
     }
 
     @Override
     public void updateMessageCompleted(long messageId, String resolution, Date timestamp) {
-        updateMessageStatus("completed_timestamp", messageId, resolution, timestamp);
-    }
-
-    private void updateMessageStatus(String timestampColumn, long messageId, String resolution, Date timestamp) {
+        // duplicate code with updateMessageStarted to avoid SQL injection issue for sonar
         try (Connection con = dataSource.getConnection()) {
             try {
                 con.setAutoCommit(false);
-                String sql = "UPDATE message SET " + timestampColumn + " = ? WHERE message_id = ?";
+                String sql = "UPDATE message SET completed_timestamp = ? WHERE message_id = ?";
                 try (PreparedStatement ps = con.prepareStatement(sql)) {
                     ps.setTimestamp(1, new Timestamp(timestamp.getTime()));
                     ps.setLong(2, messageId);
@@ -92,6 +106,7 @@ public class MessageDaoImpl implements MessageDao {
         } catch (SQLException e) {
             throw new RuntimeException("Error updating message status in DB: " + e.getMessage(), e);
         }
+
     }
 
     @Override
index 89f29b3..a07b3c4 100644 (file)
@@ -180,10 +180,12 @@ public class MessageInterceptorImpl implements MessageInterceptor {
     private Event waitForNewAction(int holdTime) {
         long startTime = System.currentTimeMillis();
         long currentTime = startTime;
-        while (currentTime - startTime <= (holdTime + 1) * 1000) {
+        while (currentTime - startTime <= (holdTime + 1) * 1000L) {
             try {
                 Thread.sleep(5000);
-            } catch (Exception e) {
+            } catch (InterruptedException e) {
+                log.info("Break sleep : " + e.getMessage());
+                Thread.currentThread().interrupt();
             }
 
             MessageAction nextAction = messageDao.getNextAction(message.getMessageId());
index b2f69db..5fc06cb 100644 (file)
@@ -104,6 +104,7 @@ public class MessageQueueTest {
                 try {
                     Thread.sleep(startTime);
                 } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
                 }
 
                 MessageData r = interceptor.processRequest(request);
@@ -112,6 +113,7 @@ public class MessageQueueTest {
                     try {
                         Thread.sleep(processTime);
                     } catch (InterruptedException e) {
+                        Thread.currentThread().interrupt();
                     }
 
                     interceptor.processResponse(response);
@@ -158,6 +160,7 @@ public class MessageQueueTest {
             try {
                 Thread.sleep(processTime);
             } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
             }
         }
     }
index 2cdef35..9016579 100644 (file)
@@ -415,7 +415,9 @@ public class NpmServiceManagerImpl implements NpmServiceManager {
         try {\r
             logger.trace("Initializing NPM Configurations from:({})", configFilePath);\r
             if (new File(configFilePath).exists()) {\r
-                npmConfigurations.load(new FileInputStream(configFilePath));\r
+                try (FileInputStream configInputStream = new FileInputStream(configFilePath)) {\r
+                    npmConfigurations.load(configInputStream);\r
+                }\r
             } else {\r
                 logger.warn("Config File:({}) not found, Initializing NPM with default configurations.", configFilePath);\r
                 configFilePath = "properties" + File.separator + NpmConstants.NPM_CONFIG_PROPERTIES_FILE_NAME;\r
index 735d6d9..8b74e31 100644 (file)
@@ -61,7 +61,7 @@ public class NpmUtils {
             mapper.enable(SerializationFeature.INDENT_OUTPUT);\r
             return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(instance);\r
         } catch (JsonProcessingException e) {\r
-            e.printStackTrace();\r
+            logger.warn(e.getMessage(), e);\r
         }\r
         return null;\r
     }\r
index 63fe111..a63b7d4 100644 (file)
@@ -84,6 +84,7 @@ public class LockHelperImpl implements LockHelper {
                 try {
                     Thread.sleep(lockWait * 1000L);
                 } catch (InterruptedException ex) {
+                    Thread.currentThread().interrupt();
                 }
             }
         }
index e927000..4199778 100644 (file)
@@ -1,5 +1,6 @@
 package org.onap.ccsdk.features.lib.rlock;
 
+import java.security.SecureRandom;
 import java.util.Collection;
 import java.util.HashSet;
 import java.util.Set;
@@ -99,6 +100,7 @@ public abstract class SynchronizedFunction {
     }
 
     private static String generateLockRequester() {
-        return "SynchronizedFunction-" + (int) (Math.random() * 1000000);
+        SecureRandom random = new SecureRandom();
+        return "SynchronizedFunction-" + (random.nextInt() % 1000000);
     }
 }
index cce377e..4f205d1 100644 (file)
@@ -42,6 +42,7 @@ public class TestLockHelper {
             try {
                 Thread.sleep(500);
             } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
                 log.warn("Thread interrupted: " + e.getMessage(), e);
             }
 
index 1756615..0d9cc8f 100644 (file)
@@ -146,20 +146,16 @@ public class AddCMHandleProvider implements CMHandleAPIService, NetconfNodeState
         // GET configuration from properties file
         config = new HashMap<String, String>();
 
-        try {
-            FileInputStream fileInput = new FileInputStream(propDir + PROPERTIES_FILE_NAME);
+        try (FileInputStream fileInput = new FileInputStream(propDir + PROPERTIES_FILE_NAME)) {
             Properties properties = new Properties();
             properties.load(fileInput);
-            fileInput.close();
 
             for (String param : new String[] {"url", "user", "password",
                     "authentication, dmi-service-name"}) {
                 config.put(param, properties.getProperty(param));
             }
-        } catch (FileNotFoundException e) {
-            e.printStackTrace();
         } catch (IOException e) {
-            e.printStackTrace();
+            LOG.error("Error while reading properties file: ", e);
         }
 
         LOG.info("addCMHandle Session Initiated");
@@ -167,7 +163,7 @@ public class AddCMHandleProvider implements CMHandleAPIService, NetconfNodeState
 
     @Override
     public void onCreated(NodeId nNodeId, NetconfNode netconfNode) {
-        LOG.info("NetConf device connected ", nNodeId.getValue());
+        LOG.info("NetConf device connected {}", nNodeId.getValue());
         JSONObject obj = new JSONObject();
         obj.put("cm-handle-id", nNodeId.getValue());
         obj.put("dmi-service-name", config.get("dmi-service-name"));
@@ -178,7 +174,7 @@ public class AddCMHandleProvider implements CMHandleAPIService, NetconfNodeState
         String authenticationMethod = config.get("authentication");
         ClientResponse response = null;
         try {
-            if (authenticationMethod.equals("basic")) {
+            if ("basic".equals(authenticationMethod)) {
                 LOG.debug("Sending message to dmaap-message-router: {}", obj.toString());
                 dmaapClient.addFilter(new HTTPBasicAuthFilter(config.get("user"), config.get("password")));
 
@@ -188,11 +184,11 @@ public class AddCMHandleProvider implements CMHandleAPIService, NetconfNodeState
                 response = dmaapClient.resource(config.get("url")).type(MediaType.APPLICATION_JSON)
                         .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, obj);
             }
+            LOG.info("Received response from dmaap-message-router: \n {}", response.toString());
         } catch (Exception e) {
-            LOG.error("Error while posting message to CM_HANDLE topic: {}", e);
+            LOG.error("Error while posting message to CM_HANDLE topic: ", e);
         }
 
-        LOG.info("Received response from dmaap-message-router: \n {}", response.toString());
     }
 
     @Override
index b580b53..afc22c9 100644 (file)
@@ -112,8 +112,7 @@ public class EnergysavingsProvider implements EnergysavingsService {
         HashMap<String, String> dmaapPolicyHttpParams = new HashMap<String, String>();
         HashMap<String, String> energySavingsServerHttpParams = new HashMap<String, String>();
 
-        try {
-            FileInputStream fileInput = new FileInputStream(propDir + PROPERTIES_FILE_NAME);
+        try (FileInputStream fileInput = new FileInputStream(propDir + PROPERTIES_FILE_NAME)) {
             Properties properties = new Properties();
             properties.load(fileInput);
             fileInput.close();
@@ -123,9 +122,9 @@ public class EnergysavingsProvider implements EnergysavingsService {
                 energySavingsServerHttpParams.put(param, properties.getProperty("energySavingsServer." + param));
             }
         } catch (FileNotFoundException e) {
-            e.printStackTrace();
+            LOG.error("Unexpected value for energy savings server authentication: ");
         } catch (IOException e) {
-            e.printStackTrace();
+            LOG.error("Unexpected value for energy savings server authentication: ");
         }
 
         // Create a web resource for the Energy Savings server