Code cleanup to resolve critical sonar issues 65/7765/9
authorMagnusen, Drew (dm741q) <dm741q@att.com>
Wed, 16 Aug 2017 20:21:15 +0000 (15:21 -0500)
committerMagnusen, Drew (dm741q) <dm741q@att.com>
Fri, 18 Aug 2017 19:40:18 +0000 (14:40 -0500)
Code cleanup mostly involed directing the output of exception messages
to the correct logger stream.

Issue-ID: [POLICY-115]
Change-Id: I2042bac3d3b0991a2ebed33421a73f1aa300c7c1
Signed-off-by: Magnusen, Drew (dm741q) <dm741q@att.com>
14 files changed:
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopLogger.java
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ControlLoopPublisher.java
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopEventManager.java
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ControlLoopOperationManager.java
controlloop/common/guard/src/main/java/org/onap/policy/guard/CallGuardTask.java
controlloop/common/guard/src/main/java/org/onap/policy/guard/PIPEngineGetHistory.java
controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardXacmlHelper.java
controlloop/common/guard/src/main/java/org/onap/policy/guard/PolicyGuardYamlToXacml.java
controlloop/common/model-impl/aai/src/main/java/org/onap/policy/aai/AAINQF199/AAINQF199Manager.java
controlloop/common/model-impl/appc/src/main/java/org/onap/policy/appc/util/Serialization.java
controlloop/common/model-impl/events/src/main/java/org/onap/policy/controlloop/util/Serialization.java
controlloop/common/model-impl/mso/src/main/java/org/onap/policy/mso/MSOManager.java
controlloop/common/model-impl/rest/src/main/java/org/onap/policy/rest/RESTManager.java
pom.xml

index 4495f2a..bb23983 100644 (file)
@@ -22,6 +22,10 @@ package org.onap.policy.controlloop;
 
 import java.lang.reflect.Constructor;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
 public interface ControlLoopLogger {
        
        public void info(String... parameters);
@@ -32,13 +36,17 @@ public interface ControlLoopLogger {
        
        public static class Factory {
                
-               public ControlLoopLogger buildLogger(String className) {
+               private static final Logger logger = LoggerFactory.getLogger(Factory.class);
+               
+                               
+               public ControlLoopLogger buildLogger(String className) throws ControlLoopException {
+                       
                        try {
                                Constructor<?> constr = Class.forName(className).getConstructor();
                                return (ControlLoopLogger) constr.newInstance();
                        } catch (Exception e) {
-                               e.printStackTrace();
-                               throw new RuntimeException("Cannot load class " + className);
+                               logger.error("buildLogger threw: ", e);
+                               throw new ControlLoopException("Cannot load class " + className);
                        }
                }
                
index 3ed6f8d..9272e28 100644 (file)
@@ -22,19 +22,24 @@ package org.onap.policy.controlloop;
 
 import java.lang.reflect.Constructor;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 public interface ControlLoopPublisher {
        
        public void     publish(Object object);
        
        public static class Factory {
+               private static final Logger logger = LoggerFactory.getLogger(Factory.class);
                
-               public ControlLoopPublisher buildLogger(String className) {
+                               
+               public ControlLoopPublisher buildLogger(String className) throws ControlLoopException {
                        try {
                                Constructor<?> constr = Class.forName(className).getConstructor();
                                return (ControlLoopPublisher) constr.newInstance();
                        } catch (Exception e) {
-                               e.printStackTrace();
-                               throw new RuntimeException("Cannot load class " + className);
+                               logger.error("ControlLoopPublisher.buildLogger threw: ", e);
+                               throw new ControlLoopException("Cannot load class " + className);
                        }
                }
                
index d1d2cef..3feab7d 100644 (file)
@@ -33,7 +33,6 @@ import org.onap.policy.controlloop.ControlLoopNotificationType;
 import org.onap.policy.controlloop.ControlLoopOperation;
 import org.onap.policy.controlloop.VirtualControlLoopEvent;
 import org.onap.policy.controlloop.VirtualControlLoopNotification;
-
 import org.onap.policy.controlloop.ControlLoopException;
 import org.onap.policy.controlloop.policy.FinalResult;
 import org.onap.policy.controlloop.policy.Policy;
@@ -43,12 +42,16 @@ import org.onap.policy.guard.LockCallback;
 import org.onap.policy.guard.PolicyGuard;
 import org.onap.policy.guard.PolicyGuard.LockResult;
 import org.onap.policy.guard.TargetLock;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class ControlLoopEventManager implements LockCallback, Serializable {
        
        /**
         * 
         */
+       private static final Logger logger = LoggerFactory.getLogger(ControlLoopEventManager.class);
+       
        private static final long serialVersionUID = -1216568161322872641L;
        public final String closedLoopControlName;
        public final UUID requestID;
@@ -62,11 +65,11 @@ public class ControlLoopEventManager implements LockCallback, Serializable {
        private FinalResult controlLoopTimedOut = null;
 
        private boolean isActivated = false;
-       private LinkedList<ControlLoopOperation> controlLoopHistory = new LinkedList<ControlLoopOperation>();
+       private LinkedList<ControlLoopOperation> controlLoopHistory = new LinkedList<>();
        private ControlLoopOperationManager currentOperation = null;
        private TargetLock targetLock = null;
        
-       private static Collection<String> requiredAAIKeys = new ArrayList<String>();
+       private static Collection<String> requiredAAIKeys = new ArrayList<>();
        static {
                requiredAAIKeys.add("AICVServerSelfLink");
                requiredAAIKeys.add("AICIdentity");
@@ -148,6 +151,7 @@ public class ControlLoopEventManager implements LockCallback, Serializable {
                        //
                        this.isActivated = true;
                } catch (ControlLoopException e) {
+                       logger.error("{}: activate threw: ",this, e);
                        notification.notification = ControlLoopNotificationType.REJECTED;
                        notification.message = e.getMessage();
                }
@@ -183,6 +187,7 @@ public class ControlLoopEventManager implements LockCallback, Serializable {
                                        yamlSpecification = decodedYaml;
                                }
                        } catch (UnsupportedEncodingException e) {
+                               logger.error("{}: activate threw: ",this, e);
                        }
                        //
                        // Parse the YAML specification
@@ -203,6 +208,7 @@ public class ControlLoopEventManager implements LockCallback, Serializable {
                        //
                        this.isActivated = true;
                } catch (ControlLoopException e) {
+                       logger.error("{}: activate threw: ",this, e);
                        notification.notification = ControlLoopNotificationType.REJECTED;
                        notification.message = e.getMessage();
                }
@@ -467,6 +473,7 @@ public class ControlLoopEventManager implements LockCallback, Serializable {
                                return NEW_EVENT_STATUS.SYNTAX_ERROR;
                        }
                } catch (ControlLoopException e) {
+                       logger.error("{}: onNewEvent threw: ",this, e);
                        return NEW_EVENT_STATUS.SYNTAX_ERROR;
                }
        }
index ff7b2c7..f552cc5 100644 (file)
@@ -30,15 +30,15 @@ import javax.persistence.Persistence;
 
 import org.onap.policy.appc.Response;
 import org.onap.policy.appc.ResponseCode;
-
 import org.onap.policy.controlloop.ControlLoopEvent;
 import org.onap.policy.controlloop.ControlLoopOperation;
 import org.onap.policy.controlloop.VirtualControlLoopEvent;
-
 import org.onap.policy.controlloop.ControlLoopException;
 import org.onap.policy.controlloop.policy.Policy;
 import org.onap.policy.controlloop.policy.PolicyResult;
 import org.onap.policy.controlloop.actor.appc.APPCActorServiceProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 
 public class ControlLoopOperationManager implements Serializable {
@@ -47,6 +47,7 @@ public class ControlLoopOperationManager implements Serializable {
         * 
         */
        private static final long serialVersionUID = -3773199283624595410L;
+       private static final Logger logger = LoggerFactory.getLogger(ControlLoopOperationManager.class);
 
        @Override
        public String toString() {
@@ -449,7 +450,7 @@ public class ControlLoopOperationManager implements Serializable {
                try{
                        em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();//emf.createEntityManager();           
                }catch(Exception e){
-                       System.err.println("Test thread got Exception " + e.getLocalizedMessage() + " Can't write to Operations History DB.");
+                       logger.error("storeOperationInDataBase threw: ", e);
                        return; 
                }
                        
index dbef0c4..53e9729 100644 (file)
@@ -23,13 +23,17 @@ package org.onap.policy.guard;
 import com.att.research.xacml.api.DataTypeException;
 import com.att.research.xacml.api.pdp.PDPEngine;
 import com.att.research.xacml.std.annotations.RequestParser;
+
 import java.util.UUID;
 
 import org.drools.core.WorkingMemory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 
 public class CallGuardTask implements Runnable {
        
+       private static final Logger logger = LoggerFactory.getLogger(CallGuardTask.class);
        WorkingMemory workingMemory;
        PDPEngine embeddedPdpEngine;
        String restfulPdpUrl;
@@ -59,8 +63,7 @@ public class CallGuardTask implements Runnable {
        try {
                request = RequestParser.parseRequest(xacmlReq);
                } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) {
-                       // TODO Auto-generated catch block
-                       e.printStackTrace();
+                       logger.error("CallGuardTask.run threw: ", e);
                } 
        
                
index 8f3928c..57deee5 100644 (file)
@@ -47,15 +47,16 @@ import com.att.research.xacml.api.Attribute;
 import com.att.research.xacml.api.AttributeValue;
 import com.att.research.xacml.api.Identifier;
 import com.att.research.xacml.std.datatypes.DataTypes;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 
 
 public class PIPEngineGetHistory extends StdConfigurableEngine{
 
-       private Log logger                                                      = LogFactory.getLog(this.getClass());
        
+       private static final Logger logger = LoggerFactory.getLogger(PIPEngineGetHistory.class);
        //private static EntityManager em;
        
        public static final String DEFAULT_DESCRIPTION          = "PIP for retrieving Operations History from DB";
@@ -88,7 +89,7 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{
                try {
                        attributeValue  = DataTypes.DT_INTEGER.createAttributeValue(value);
                } catch (Exception ex) {
-                       this.logger.error("Failed to convert " + value + " to an AttributeValue<Boolean>", ex);
+                       this.logger.error("Failed to convert {} to an AttributeValue<Boolean>",value, ex);
                }
                if (attributeValue != null) {
                        stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, pipRequest.getIssuer()/*this.getIssuer()*/, false));
@@ -193,7 +194,7 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{
                                pipResponse     = null;
                        }
                } catch (PIPException ex) {
-                       System.out.println("PIPException getting subject-id attribute: " + ex.getMessage());                    
+                       logger.error("getAttribute threw: ", ex);
                }
                return pipResponse;
        }
@@ -295,29 +296,28 @@ public class PIPEngineGetHistory extends StdConfigurableEngine{
                try{
                        em = Persistence.createEntityManagerFactory("OperationsHistoryPU").createEntityManager();
                }catch(Exception e){
-                       System.err.println("PIP thread got Exception " + e.getLocalizedMessage() + " Can't connect to Operations History DB.");
+                       logger.error("getCountFromDB threw: ", e);
                        return -1;
                }
                
-               String sql = "select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor='"
-                               + actor
-                               + "' and operation='"
-                               + operation
-                               + "' and target='"
-                               + target
-                               + "' "
-                               + "and endtime between date_sub(now(),interval "
-                               + timeWindow
-                               + ") and now()";
-               
-               Query nq = em.createNativeQuery(sql);
+               String sql = "select count(*) as count from operationshistory10 where outcome<>'Failure_Guard'"
+                               + " and actor=:actor" 
+                               + " and operation=:operation" 
+                               + " and target=:target" 
+                               + " and endtime between date_sub(now(),interval :timeWindow) and now()"; 
+               Query nq = em.createNativeQuery(sql); 
+               nq = nq.setParameter("actor", actor); 
+               nq = nq.setParameter("operation", operation); 
+               nq = nq.setParameter("target", target); 
+               nq = nq.setParameter("timeWindow", timeWindow);
                
                int ret = -1;
                try{
                        ret = ((Number)nq.getSingleResult()).intValue();
                }
                catch(NoResultException | NonUniqueResultException ex){
-                       System.err.println("PIP thread got Exception " + ex.getLocalizedMessage());
+                       logger.error("getCountFromDB threw: ", ex);
                        return -1;
                }
                
index 20d50fd..c0ed800 100644 (file)
@@ -30,6 +30,8 @@ import java.util.UUID;
 
 import org.apache.commons.io.IOUtils;
 import org.apache.http.entity.ContentType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import com.att.research.xacml.api.Attribute;
 import com.att.research.xacml.api.AttributeCategory;
@@ -44,7 +46,7 @@ import com.att.research.xacml.std.json.JSONResponse;
 
 public class PolicyGuardXacmlHelper {
        
-       
+       private static final Logger logger = LoggerFactory.getLogger(PolicyGuardXacmlHelper.class);
 
        public static com.att.research.xacml.api.Response callPDP(PDPEngine xacmlEmbeddedPdpEngine, String restfulPdpUrl, com.att.research.xacml.api.Request request, boolean isREST) {
                //
@@ -133,19 +135,20 @@ public class PolicyGuardXacmlHelper {
                                                contentType.getMimeType().equalsIgnoreCase("application/xacml+xml") ) {
                                response = (com.att.research.xacml.api.Response) DOMResponse.load(connection.getInputStream());
                                } else {
-                                       System.err.println("unknown content-type: " + contentType);
+                                       logger.error("{}: unknown content-type: ", contentType);
                        }
 
                 } catch (Exception e) {
                                String message = "Parsing Content-Type: " + connection.getContentType() + ", error=" + e.getMessage();
-                               System.err.println(message);
+                               logger.error("{}: callRESTfulPDP threw: ", message);
                        }
 
             } else {
-               System.err.println(connection.getResponseCode() + " " + connection.getResponseMessage());
+               logger.error("unknown content-type: {} {}", connection.getResponseCode(), connection.getResponseMessage() );
             }
                } catch (Exception e) {
-                       System.err.println(e);
+                       
+                       logger.error("callRESTfulPDP threw: ", e);
                }
                
                return response;
index 4d952b5..21584f0 100644 (file)
@@ -30,11 +30,14 @@ import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
 import org.onap.policy.controlloop.policy.guard.ControlLoopGuard;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 
 
 public class PolicyGuardYamlToXacml {
        
+       private static final Logger logger = LoggerFactory.getLogger(PolicyGuardYamlToXacml.class);
        
        public static void fromYamlToXacml(String yamlFile, String xacmlTemplate, String xacmlPolicyOutput){
                
@@ -67,8 +70,7 @@ public class PolicyGuardYamlToXacml {
                Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes());
         
                } catch (IOException e) {
-                       // TODO Auto-generated catch block
-                       e.printStackTrace();
+                       logger.error("fromYamlToXacml threw: ", e);
                }
                
        }
@@ -198,8 +200,7 @@ public class PolicyGuardYamlToXacml {
                Files.write(Paths.get(xacmlPolicyOutput), xacmlPolicyContent.getBytes());
         
                } catch (IOException e) {
-                       // TODO Auto-generated catch block
-                       e.printStackTrace();
+                       logger.error("fromYamlToXacmlBlacklist threw: ", e);
                }
                
        }
index e02021a..b079122 100644 (file)
@@ -28,10 +28,13 @@ import org.onap.policy.aai.AAIGETResponse;
 import org.onap.policy.aai.util.Serialization;
 import org.onap.policy.rest.RESTManager;
 import org.onap.policy.rest.RESTManager.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import com.google.gson.JsonSyntaxException;
 
 public final class AAINQF199Manager {
+       private static final Logger logger = LoggerFactory.getLogger(AAINQF199Manager.class);
        
        public static AAINQF199Response postQuery(String url, String username, String password, AAINQF199Request request, UUID requestID) {
                
@@ -57,7 +60,7 @@ public final class AAINQF199Manager {
                                AAINQF199Response response = Serialization.gsonPretty.fromJson(httpDetails.b, AAINQF199Response.class);
                                return response;
                        } catch (JsonSyntaxException e) {
-                               System.err.println("Failed to deserialize into AAIResponse" + e.getLocalizedMessage());
+                               logger.error("postQuery threw: ", e);
                        }
                }
 
@@ -93,7 +96,7 @@ public final class AAINQF199Manager {
                                        responseGet = Serialization.gsonPretty.fromJson(httpDetailsGet.b, AAIGETResponse.class);
                                        return responseGet;
                                } catch (JsonSyntaxException e) {
-                                       System.err.println("Failed to deserialize into AAIResponse" + e.getLocalizedMessage());
+                                       logger.error("getQuery threw: ", e);
                                }
                        }
                        try {
index 8a801c3..be7a66a 100644 (file)
@@ -25,6 +25,9 @@ import java.time.Instant;
 import java.time.ZonedDateTime;
 import java.time.format.DateTimeFormatter;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import com.google.gson.JsonDeserializationContext;
@@ -37,16 +40,17 @@ import com.google.gson.JsonSerializer;
 
 public final class Serialization {
        
-       public static DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSxxx");
+       public static final DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSxxx");
 
        public static class gsonUTCAdapter implements JsonSerializer<ZonedDateTime>, JsonDeserializer<ZonedDateTime> {
-
+               private static final Logger logger = LoggerFactory.getLogger(gsonUTCAdapter.class);
+               
                public ZonedDateTime deserialize(JsonElement element, Type type, JsonDeserializationContext context)
                                throws JsonParseException {
                        try {
                                return ZonedDateTime.parse(element.getAsString(), format);
                        } catch (Exception e) {
-                               System.err.println(e);
+                               logger.error("deserialize threw: ", e);
                        }
                        return null;
                }
index a459477..9e6d1af 100644 (file)
@@ -73,7 +73,7 @@ public final class Serialization {
        }
        
        public static class gsonUTCAdapter implements JsonSerializer<ZonedDateTime>, JsonDeserializer<ZonedDateTime> {
-               public static DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSxxx");
+               public static final DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSxxx");
 
                public ZonedDateTime deserialize(JsonElement element, Type type, JsonDeserializationContext context)
                                throws JsonParseException {
index 7972590..81d43ef 100644 (file)
@@ -26,11 +26,15 @@ import java.util.Map;
 import org.onap.policy.mso.util.Serialization;
 import org.onap.policy.rest.RESTManager;
 import org.onap.policy.rest.RESTManager.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import com.google.gson.JsonSyntaxException;
 
 public final class MSOManager {
 
+       private static final Logger logger = LoggerFactory.getLogger(MSOManager.class);
+       
        public static MSOResponse createModuleInstance(String url, String urlBase, String username, String password, MSORequest request) {
                
                //
@@ -87,9 +91,9 @@ public final class MSOManager {
                                System.out.println("***** ########  VF Module Creation timeout. Status: ("+responseGet.request.requestStatus.requestState+")");
                                return responseGet;
                        } catch (JsonSyntaxException e) {
-                               System.err.println("Failed to deserialize into MSOResponse" + e.getLocalizedMessage());
+                               logger.error("Failed to deserialize into MSOResponse: ", e);
                        } catch (InterruptedException e) {
-                               System.err.println("Interrupted exception: " + e.getLocalizedMessage());
+                               logger.error("Interrupted exception: ", e);
                        }
                }
                
index e42ab16..8c79d2a 100644 (file)
@@ -34,9 +34,13 @@ import org.apache.http.impl.client.BasicCredentialsProvider;
 import org.apache.http.impl.client.CloseableHttpClient;
 import org.apache.http.impl.client.HttpClientBuilder;
 import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public final class RESTManager {
 
+       private static final Logger logger = LoggerFactory.getLogger(RESTManager.class);
+       
        public static class Pair<A, B> {
                public final A a;
                public final B b;
@@ -81,7 +85,8 @@ public final class RESTManager {
 
                        return new Pair<Integer, String>(response.getStatusLine().getStatusCode(), returnBody);
                } catch (IOException e) {
-                       System.err.println("Failed to POST to " + url + e.getLocalizedMessage());
+                       logger.error("Failed to POST to {}",url,e);
+
                        return null;
                }
                
@@ -108,7 +113,7 @@ public final class RESTManager {
 
                        return new Pair<Integer, String>(response.getStatusLine().getStatusCode(), returnBody);
                } catch (IOException e) {
-                       System.err.println("Failed to GET to " + url + e.getLocalizedMessage());
+                       logger.error("Failed to GET to {}",url,e);
                        return null;
                }
        }
diff --git a/pom.xml b/pom.xml
index 35d3410..294d91f 100644 (file)
--- a/pom.xml
+++ b/pom.xml
            </plugin>
          </plugins>
        </reporting>
+       <dependencies>
+               <dependency>
+               <groupId>ch.qos.logback</groupId>
+               <artifactId>logback-classic</artifactId>
+               <version>1.2.3</version>
+               <scope>provided</scope>
+               </dependency>
+       </dependencies>
 </project>