Fix sonar blocker/critical 31/13131/1
authorPamela Dragosh <pdragosh@research.att.com>
Fri, 15 Sep 2017 22:27:29 +0000 (18:27 -0400)
committerPamela Dragosh <pdragosh@research.att.com>
Mon, 18 Sep 2017 12:14:07 +0000 (08:14 -0400)
Also add back .gitignore
Sonar blocker for change condition always true. Easier to re-write
this using try-with-resources.
Use synchronized static method to set a static variable.
Don't use e.printStackTrace it causes sonar critical to log exception
Log the bytes read. Ideally I would re-write this using Java 8 NIO

Issue-ID: POLICY-195
Change-Id: I080d1ad4c8bea91f87c3eca109325700e1589558
Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
.gitignore [new file with mode: 0644]
feature-healthcheck/.gitignore [new file with mode: 0644]
feature-healthcheck/src/test/java/org/onap/policy/drools/healthcheck/HealthCheckFeatureTest.java
feature-state-management/.gitignore [new file with mode: 0644]
feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DbAudit.java
feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DroolsPDPIntegrityMonitor.java
feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/IntegrityMonitorRestManager.java
feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/RepositoryAudit.java
feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeature.java
feature-state-management/src/test/java/org/onap/policy/drools/statemanagement/test/StateManagementTest.java

diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..30e6052
--- /dev/null
@@ -0,0 +1,15 @@
+.DS_Store
+.project
+.settings
+.classpath
+.jupiter
+.pydevproject
+*.swp
+*.log
+*.out
+.metadata/
+target/
+*/logs/
+*/sql/
+*/testingLogs/
+*/config/
diff --git a/feature-healthcheck/.gitignore b/feature-healthcheck/.gitignore
new file mode 100644 (file)
index 0000000..b83d222
--- /dev/null
@@ -0,0 +1 @@
+/target/
index a618f03..1c0b45f 100644 (file)
@@ -22,28 +22,20 @@ package org.onap.policy.drools.healthcheck;
 
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 
 import java.io.File;
-import java.io.FileOutputStream;
 import java.io.FileWriter;
-import java.io.OutputStream;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
 import java.util.Properties;
 
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.onap.policy.drools.healthcheck.HealthCheck.Report;
 import org.onap.policy.drools.healthcheck.HealthCheck.Reports;
-import org.onap.policy.drools.http.client.HttpClient;
-import org.onap.policy.drools.http.server.HttpServletServer;
 import org.onap.policy.drools.persistence.SystemPersistence;
 import org.onap.policy.drools.properties.PolicyProperties;
 import org.onap.policy.drools.system.PolicyEngine;
diff --git a/feature-state-management/.gitignore b/feature-state-management/.gitignore
new file mode 100644 (file)
index 0000000..b83d222
--- /dev/null
@@ -0,0 +1 @@
+/target/
index a86ac8e..efecf88 100644 (file)
@@ -44,6 +44,9 @@ public class DbAudit extends DroolsPDPIntegrityMonitor.AuditBase
   // invoked -- doing this avoids the need to create the table in advance.
   static private boolean createTableNeeded = true;
 
+  synchronized private static void setCreateTableNeeded(boolean b) {
+               DbAudit.createTableNeeded = b;
+       }
   /**
    * @return the single 'DbAudit' instance
    */
@@ -98,26 +101,17 @@ public class DbAudit extends DroolsPDPIntegrityMonitor.AuditBase
        String user = properties.getProperty(StateManagementProperties.DB_USER);
        String password = properties.getProperty(StateManagementProperties.DB_PWD);
 
-       // connection to DB
-       Connection connection = null;
-
-       // supports SQL operations
-       PreparedStatement statement = null;
-       ResultSet rs = null;
-
        // operation phase currently running -- used to construct an error
        // message, if needed
        String phase = null;
 
-       try
+       // create connection to DB
+       phase = "creating connection";
+       if(logger.isDebugEnabled()){
+               logger.debug("DbAudit: Creating connection to {}", url);
+       }
+       try (Connection connection = DriverManager.getConnection(url, user, password))
          {
-               // create connection to DB
-               phase = "creating connection";
-               if(logger.isDebugEnabled()){
-                       logger.debug("DbAudit: Creating connection to {}", url);
-               }
-
-               connection = DriverManager.getConnection(url, user, password);
 
                // create audit table, if needed
                if (createTableNeeded)
@@ -126,93 +120,68 @@ public class DbAudit extends DroolsPDPIntegrityMonitor.AuditBase
                        if(logger.isDebugEnabled()){
                                logger.info("DbAudit: Creating 'Audit' table, if needed");
                        }
-                       statement = connection.prepareStatement
+                       try (PreparedStatement statement = connection.prepareStatement
                          ("CREATE TABLE IF NOT EXISTS Audit (\n"
                           + " name varchar(64) DEFAULT NULL,\n"
                           + " UNIQUE KEY name (name)\n"
-                          + ") DEFAULT CHARSET=latin1;");
-                       statement.execute();
-                       statement.close();
-                       createTableNeeded = false;
+                          + ") DEFAULT CHARSET=latin1;")) {
+                               statement.execute();
+                               DbAudit.setCreateTableNeeded(false);
+                       } catch (Exception e) {
+                               throw e;
+                       }
                  }
 
                // insert an entry into the table
                phase = "insert entry";
                String key = UUID.randomUUID().toString();
-               statement = connection.prepareStatement
-                 ("INSERT INTO Audit (name) VALUES (?)");
-               statement.setString(1, key);
-               statement.executeUpdate();
-               statement.close();
-
+               try (PreparedStatement statement = connection.prepareStatement
+                 ("INSERT INTO Audit (name) VALUES (?)")) {
+                       statement.setString(1, key);
+                       statement.executeUpdate();
+               } catch (Exception e) {
+                       throw e;
+               }
+               
                // fetch the entry from the table
                phase = "fetch entry";
-               statement = connection.prepareStatement
-                 ("SELECT name FROM Audit WHERE name = ?");
-               statement.setString(1, key);
-               rs = statement.executeQuery();
-               if (rs.first())
-                 {
-                       // found entry
-                       if(logger.isDebugEnabled()){
-                               logger.debug("DbAudit: Found key {}", rs.getString(1));
+               try (PreparedStatement statement = connection.prepareStatement
+                 ("SELECT name FROM Audit WHERE name = ?")) {
+                       statement.setString(1, key);
+                       try (ResultSet rs = statement.executeQuery()) {
+                               if (rs.first())
+                                 {
+                                       // found entry
+                                       if(logger.isDebugEnabled()){
+                                               logger.debug("DbAudit: Found key {}", rs.getString(1));
+                                       }
+                                 }
+                               else
+                                 {
+                                       logger.error
+                                         ("DbAudit: can't find newly-created entry with key {}", key);
+                                       setResponse("Can't find newly-created entry");
+                                 }
+                       } catch (Exception e) {
+                               throw e;
                        }
-                 }
-               else
-                 {
-                       logger.error
-                         ("DbAudit: can't find newly-created entry with key {}", key);
-                       setResponse("Can't find newly-created entry");
-                 }
-               statement.close();
-
+               }
                // delete entries from table
                phase = "delete entry";
-               statement = connection.prepareStatement
-                 ("DELETE FROM Audit WHERE name = ?");
-               statement.setString(1, key);
-               statement.executeUpdate();
-               statement.close();
-               statement = null;
-         }
+               try (PreparedStatement statement = connection.prepareStatement
+                 ("DELETE FROM Audit WHERE name = ?")) {
+                       statement.setString(1, key);
+                       statement.executeUpdate();
+               } catch (Exception e) {
+                       throw e;
+               }
+       }
        catch (Exception e)
          {
                String message = "DbAudit: Exception during audit, phase = " + phase;
                logger.error(message, e);
                setResponse(message);
          }
-       finally
-         {
-               if (rs != null)
-                 {
-                       try
-                         {
-                               rs.close();
-                         }
-                       catch (Exception e)
-                         {
-                         }
-                 }
-               if (statement != null)
-                 {
-                       try
-                         {
-                               statement.close();
-                         }
-                       catch (Exception e)
-                         {
-                         }
-                 }
-               if (connection != null)
-                 {
-                       try
-                         {
-                               connection.close();
-                         }
-                       catch (Exception e)
-                         {
-                         }
-                 }
-         }
   }
+
 }
index 73f6f73..2dc2e26 100644 (file)
 
 package org.onap.policy.drools.statemanagement;
 
-import java.io.File;
-import java.io.FileInputStream;
 import java.net.InetSocketAddress;
 import java.util.ArrayList;
 import java.util.Properties;
 
 import org.onap.policy.common.im.IntegrityMonitor;
 import org.onap.policy.common.im.IntegrityMonitorException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.onap.policy.drools.core.PolicyContainer;
 import org.onap.policy.drools.http.server.HttpServletServer;
 import org.onap.policy.drools.properties.Startable;
 import org.onap.policy.drools.utils.PropertyUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * This class extends 'IntegrityMonitor' for use in the 'Drools PDP'
@@ -351,10 +348,11 @@ public class DroolsPDPIntegrityMonitor extends IntegrityMonitor
                                        try {
                                                server.waitedStart(5);
                                        } catch (Exception e) {
-                                               e.printStackTrace();
+                                               logger.error("Exception waiting for servers to start: ", e);
                                        }
                                }
                        } catch (Exception e) {
+                               logger.error("Exception building servers", e);
                                return false;
                        }
                        
@@ -366,7 +364,7 @@ public class DroolsPDPIntegrityMonitor extends IntegrityMonitor
                        try {
                                server.stop();
                        } catch (Exception e) {
-                               e.printStackTrace();
+                               logger.error("Exception during stop", e);
                        }
                        
                        return true;
index f502429..ed522fc 100644 (file)
@@ -77,8 +77,6 @@ public class IntegrityMonitorRestManager {
                                                im = DroolsPDPIntegrityMonitor.getInstance();
                                        } catch (Exception e) {
                                                logger.error("IntegrityMonitorRestManager: test() interface caught an exception", e);
-                                               e.printStackTrace();
-                                               
                                                body.append("\nException: " + e + "\n");
                                                responseValue = 500;
                                        }
index 6171572..84cb7e3 100644 (file)
@@ -335,11 +335,17 @@ public class RepositoryAudit extends DroolsPDPIntegrityMonitor.AuditBase
                // place output in 'fileContents' (replacing the Return characters
                // with Newline)
                byte[] outputData = new byte[(int)output.length()];
-               FileInputStream fis = new FileInputStream(output);
-               fis.read(outputData);
-               String fileContents = new String(outputData).replace('\r','\n');
-               fis.close();
-
+               String fileContents;
+               try (FileInputStream fis = new FileInputStream(output)) {
+                       //
+                       // Ideally this should be in a loop or even better use
+                       // Java 8 nio functionality.
+                       //
+                       int bytesRead = fis.read(outputData);
+                       logger.info("fileContents read {} bytes", bytesRead);
+                       fileContents = new String(outputData).replace('\r','\n');
+               }
+               
                // generate log messages from 'Downloading' and 'Downloaded'
                // messages within the 'mvn' output
                int index = 0;
index 6d47039..0143c58 100644 (file)
@@ -24,14 +24,13 @@ import java.io.IOException;
 import java.util.Observer;
 import java.util.Properties;
 
-import org.onap.policy.drools.statemanagement.StateManagementFeatureAPI;
 import org.onap.policy.common.im.StandbyStatusException;
 import org.onap.policy.common.im.StateManagement;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.onap.policy.drools.core.PolicySessionFeatureAPI;
 import org.onap.policy.drools.features.PolicyEngineFeatureAPI;
 import org.onap.policy.drools.utils.PropertyUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * If this feature is supported, there is a single instance of it.
@@ -100,14 +99,12 @@ public class StateManagementFeature implements StateManagementFeatureAPI,
                                }
                        }
                } catch (Exception e1) {
-                       String msg = "  \n";
                        if(logger.isDebugEnabled()){
                                logger.debug("StateManagementFeature.globalInit(): DroolsPDPIntegrityMonitor"
                                        + " initialization failed with exception:", e1);
                        }
                        logger.error("DroolsPDPIntegrityMonitor.init(): StateManagementFeature startup failed "
                                        + "to get DroolsPDPIntegrityMonitor instance:", e1);
-                       e1.printStackTrace();
                }
        }
        
index e458dce..1cd6178 100644 (file)
@@ -35,14 +35,13 @@ import org.junit.After;
 import org.junit.AfterClass;
 import org.junit.Before;
 import org.junit.BeforeClass;
-import org.junit.Ignore;
 import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.onap.policy.common.im.StateManagement;
 import org.onap.policy.drools.core.PolicySessionFeatureAPI;
 import org.onap.policy.drools.statemanagement.StateManagementFeatureAPI;
 import org.onap.policy.drools.statemanagement.StateManagementProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class StateManagementTest {