JsonRequestHandler sonar fixes 85/31085/4
authorJakub Dudycz <jakub.dudycz@nokia.com>
Fri, 9 Feb 2018 14:30:01 +0000 (15:30 +0100)
committerPatrick Brady <pb071s@att.com>
Fri, 9 Feb 2018 23:03:46 +0000 (23:03 +0000)
Change-Id: I247860dd6a91c8f8812670496289b8ae0ababf8b
Issue-ID: APPC-593
Signed-off-by: Jakub Dudycz <jakub.dudycz@nokia.com>
appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/InvalidRequestException.java [new file with mode: 0644]
appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/JsonRequestHandler.java

diff --git a/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/InvalidRequestException.java b/appc-client/client-simulator/src/main/java/org/onap/appc/simulator/client/impl/InvalidRequestException.java
new file mode 100644 (file)
index 0000000..0b80415
--- /dev/null
@@ -0,0 +1,8 @@
+package org.onap.appc.simulator.client.impl;
+
+public class InvalidRequestException extends RuntimeException{
+
+    public InvalidRequestException(String message) {
+        super(message);
+    }
+}
index 243136d..9791aa2 100644 (file)
 
 package org.onap.appc.simulator.client.impl;
 
-import org.onap.appc.client.lcm.api.AppcClientServiceFactoryProvider;
-import org.onap.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory;
-import org.onap.appc.client.lcm.api.ApplicationContext;
-import org.onap.appc.client.lcm.api.LifeCycleManagerStateful;
-import org.onap.appc.client.lcm.api.ResponseHandler;
-
-import org.onap.appc.client.lcm.exceptions.AppcClientException;
-import org.onap.appc.simulator.client.RequestHandler;
+import static java.lang.Character.toLowerCase;
+import static java.lang.Character.toUpperCase;
 
 import com.att.eelf.configuration.EELFLogger;
 import com.att.eelf.configuration.EELFManager;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.node.ObjectNode;
-
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.FileReader;
 import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.util.HashMap;
 import java.util.Properties;
+import org.onap.appc.client.lcm.api.AppcClientServiceFactoryProvider;
+import org.onap.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory;
+import org.onap.appc.client.lcm.api.ApplicationContext;
+import org.onap.appc.client.lcm.api.LifeCycleManagerStateful;
+import org.onap.appc.client.lcm.api.ResponseHandler;
+import org.onap.appc.client.lcm.exceptions.AppcClientException;
+import org.onap.appc.simulator.client.RequestHandler;
 
 public class JsonRequestHandler implements RequestHandler {
 
-     private enum modeT {
-        SYNCH,
-        ASYNCH
-    }
 
-    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
-    private String rpcName = null;
+    private final EELFLogger logger = EELFManager.getInstance().getLogger(JsonRequestHandler.class);
+    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+    private static final String INPUT_PARAM = "input";
+
     private String inputClassName = null;
     private String actionName = null;
     private String methodName = null;
-    String packageName = null;
+    private String packageName = null;
     private LifeCycleManagerStateful service = null;
     private Properties properties;
-    HashMap<String, String> exceptRpcMap = null;
-    private final EELFLogger LOG = EELFManager.getInstance().getLogger(JsonRequestHandler.class);
+    private HashMap<String, String> exceptRpcMap = null;
+
     private AppcLifeCycleManagerServiceFactory appcLifeCycleManagerServiceFactory = null;
 
+    public JsonRequestHandler() {/*default constructor*/}
 
     public JsonRequestHandler(Properties prop) throws AppcClientException {
         properties = prop;
@@ -74,21 +74,17 @@ public class JsonRequestHandler implements RequestHandler {
         try {
             service = createService();
         } catch (AppcClientException e) {
-            e.printStackTrace();
+            logger.error("An error occurred while instantiating JsonRequestHandler", e);
         }
         exceptRpcMap = prepareExceptionsMap();
     }
 
-    public  JsonRequestHandler(){
-
-    }
-
-    private HashMap<String,String> prepareExceptionsMap() {
+    private HashMap<String, String> prepareExceptionsMap() {
         exceptRpcMap = new HashMap<>();
 
         try (BufferedReader reader = new BufferedReader(
-                 new FileReader(properties.getProperty(
-                      "client.rpc.exceptions.map.file")))) {
+            new FileReader(properties.getProperty(
+                "client.rpc.exceptions.map.file")))) {
             String line;
             while ((line = reader.readLine()) != null) {
                 String[] parts = line.split(":", 2);
@@ -97,13 +93,14 @@ public class JsonRequestHandler implements RequestHandler {
                     String value = parts[1];
                     exceptRpcMap.put(key, value);
                 } else {
-                    System.out.println("ignoring line: " + line);
+                    logger.info("ignoring line: " + line);
                 }
             }
         } catch (FileNotFoundException e) {
+            logger.error("Map file not found", e);
             return exceptRpcMap;
         } catch (IOException e) {
-            e.printStackTrace();
+            logger.error("An error occurred while preparing exceptions map", e);
         }
 
         return exceptRpcMap;
@@ -120,125 +117,134 @@ public class JsonRequestHandler implements RequestHandler {
             Object input = prepareObject(inputNode);
 
             JsonResponseHandler response = new JsonResponseHandler();
-            response.setFile(source.getPath().toString());
+            response.setFile(source.getPath());
             switch (isSyncMode(inputNode)) {
-                case SYNCH: {
-                    LOG.debug("Received input request will be processed in synchronously mode");
-                    Method rpc = LifeCycleManagerStateful.class.getDeclaredMethod(methodName, input.getClass());
-                    response.onResponse(rpc.invoke(service, input));
+                case SYNCH:
+                    processSync(input, response);
                     break;
-                }
-                case ASYNCH: {
-                    LOG.debug("Received input request will be processed in asynchronously mode");
-                    Method rpc = LifeCycleManagerStateful.class.getDeclaredMethod(methodName, input.getClass(), ResponseHandler.class);
-                    rpc.invoke(service, input, response);
+                case ASYNCH:
+                    processAsync(input, response);
                     break;
-                }
-                default: {
-                    throw new RuntimeException("Unrecognized request mode");
-                }
+                default:
+                    throw new InvalidRequestException("Unrecognized request mode");
             }
-        }
-        catch(Exception ex){
-            //ex.printStackTrace();
+        } catch (Exception e) {
+            logger.error("An error occurred when proceeding file", e);
         }
 
-        LOG.debug("Action <" + actionName + "> from input file <" + source.getPath().toString() + "> processed");
+        logger.debug("Action <" + actionName + "> from input file <" + source.getPath() + "> processed");
+    }
+
+    private void processAsync(Object input, JsonResponseHandler response)
+        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
+        logger.debug("Received input request will be processed in asynchronously mode");
+        Method rpc = LifeCycleManagerStateful.class
+            .getDeclaredMethod(methodName, input.getClass(), ResponseHandler.class);
+        rpc.invoke(service, input, response);
+    }
+
+    private void processSync(Object input, JsonResponseHandler response)
+        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
+        logger.debug("Received input request will be processed in synchronously mode");
+        Method rpc = LifeCycleManagerStateful.class.getDeclaredMethod(methodName, input.getClass());
+        response.onResponse(rpc.invoke(service, input));
     }
 
     private modeT isSyncMode(JsonNode inputNode) {
         // The following solution is for testing purposes only
         // the sync/async decision logic may change upon request
         try {
-            int mode = Integer.parseInt(inputNode.findValue("input").findValue("common-header").findValue("sub-request-id").asText());
+            int mode = Integer
+                .parseInt(
+                    inputNode.findValue(INPUT_PARAM).findValue("common-header").findValue("sub-request-id").asText());
             if ((mode % 2) == 0) {
                 return modeT.SYNCH;
             }
-        }catch (Exception ex) {
+        } catch (Exception e) {
+            logger.error("Failed to parse sub-request-id", e);
             //use ASYNC as default, if value is not integer.
         }
         return modeT.ASYNCH;
     }
 
     private LifeCycleManagerStateful createService() throws AppcClientException {
-        appcLifeCycleManagerServiceFactory = AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class);
+        appcLifeCycleManagerServiceFactory = AppcClientServiceFactoryProvider
+            .getFactory(AppcLifeCycleManagerServiceFactory.class);
         return appcLifeCycleManagerServiceFactory.createLifeCycleManagerStateful(new ApplicationContext(), properties);
     }
 
-    public void shutdown(boolean isForceShutdown){
+    @Override
+    public void shutdown(boolean isForceShutdown) {
         appcLifeCycleManagerServiceFactory.shutdownLifeCycleManager(isForceShutdown);
     }
 
     public Object prepareObject(JsonNode input) {
         try {
             Class cls = Class.forName(inputClassName);
-            try {
-                // since payload is not mandatory field and not all actions contains payload
-                // so we have to check that during input parsing
-                alignPayload(input);
-            } catch (NoSuchFieldException e) {
-                LOG.debug("In " + actionName + " no payload defined");
-            }
-
-            return OBJECT_MAPPER.treeToValue(input.get("input"), cls);
-        }
-        catch(Exception ex){
-            //ex.printStackTrace();
+            tryAlignPayload(input);
+            return OBJECT_MAPPER.treeToValue(input.get(INPUT_PARAM), cls);
+        } catch (Exception ex) {
+            logger.error("Failed to prepare object", ex);
         }
         return null;
     }
 
+    private void tryAlignPayload(JsonNode input) {
+        try {
+            // since payload is not mandatory field and not all actions contains payload
+            // so we have to check that during input parsing
+            alignPayload(input);
+        } catch (NoSuchFieldException e) {
+            logger.debug("In " + actionName + " no payload defined", e);
+        }
+    }
+
     private void prepareNames(JsonNode input) throws NoSuchFieldException {
-        JsonNode inputNode = input.findValue("input");
+        JsonNode inputNode = input.findValue(INPUT_PARAM);
         actionName = inputNode.findValue("action").asText();
         if (actionName.isEmpty()) {
             throw new NoSuchFieldException("Input doesn't contains field <action>");
         }
-
-        rpcName = prepareRpcFromAction(actionName);
         inputClassName = packageName + actionName + "Input";
-        methodName = prepareMethodName(rpcName);
+        methodName = prepareMethodName(prepareRpcFromAction(actionName));
     }
 
     private void alignPayload(JsonNode input) throws NoSuchFieldException {
-        JsonNode inputNode = input.findValue("input");
+        JsonNode inputNode = input.findValue(INPUT_PARAM);
         JsonNode payload = inputNode.findValue("payload");
-        if (payload == null || payload.asText().isEmpty() || payload.toString().isEmpty())
+        if (payload == null || payload.asText().isEmpty() || payload.toString().isEmpty()) {
             throw new NoSuchFieldException("Input doesn't contains field <payload>");
+        }
 
         String payloadData = payload.asText();
-        if (payloadData.isEmpty())
+        if (payloadData.isEmpty()) {
             payloadData = payload.toString();
-        ((ObjectNode)inputNode).put("payload", payloadData);
+        }
+        ((ObjectNode) inputNode).put("payload", payloadData);
     }
 
     private String prepareRpcFromAction(String action) {
-        String rpc = checkExceptionalRpcList(action);
-        if (rpc!= null && !rpc.isEmpty()) {
-            return rpc; // we found exceptional rpc, so no need to format it
+        String exRpc = checkExceptionalRpcList(action);
+        if (exRpc != null && !exRpc.isEmpty()) {
+            return exRpc; // we found exceptional rpc, so no need to format it
         }
 
-        rpc = "";
+        StringBuilder rpc = new StringBuilder();
         boolean makeItLowerCase = true;
-        for(int i = 0; i < action.length(); i++)
-        {
-            if(makeItLowerCase) // first character will make lower case
+        for (int i = 0; i < action.length(); i++) {
+            if (makeItLowerCase) // first character will make lower case
             {
-                rpc+=Character.toLowerCase(action.charAt(i));
+                rpc.append(toLowerCase(action.charAt(i)));
                 makeItLowerCase = false;
-            }
-            else  if((i+1 < action.length()) && Character.isUpperCase(action.charAt(i+1)))
-            {
-                rpc+=action.charAt(i) + "-";
+            } else if ((i + 1 < action.length()) && Character.isUpperCase(action.charAt(i + 1))) {
+                rpc.append(action.charAt(i)).append('-');
                 makeItLowerCase = true;
-            }
-            else
-            {
-                rpc+=action.charAt(i);
+            } else {
+                rpc.append(action.charAt(i));
                 makeItLowerCase = false;
             }
         }
-        return rpc;
+        return rpc.toString();
     }
 
     private String checkExceptionalRpcList(String action) {
@@ -250,26 +256,27 @@ public class JsonRequestHandler implements RequestHandler {
 
     private String prepareMethodName(String inputRpcName) {
         boolean makeItUpperCase = false;
-        String method = "";
+        StringBuilder method = new StringBuilder();
 
-        for(int i = 0; i < inputRpcName.length(); i++)  //to check the characters of string..
+        for (int i = 0; i < inputRpcName.length(); i++)  //to check the characters of string..
         {
-            if(Character.isLowerCase(inputRpcName.charAt(i)) && makeItUpperCase) // skip first character if it lower case
+            if (Character.isLowerCase(inputRpcName.charAt(i))
+                && makeItUpperCase) // skip first character if it lower case
             {
-                method+=Character.toUpperCase(inputRpcName.charAt(i));
+                method.append(toUpperCase(inputRpcName.charAt(i)));
                 makeItUpperCase = false;
-            }
-            else  if(inputRpcName.charAt(i) == '-')
-            {
+            } else if (inputRpcName.charAt(i) == '-') {
                 makeItUpperCase = true;
-            }
-            else
-            {
-                method+=inputRpcName.charAt(i);
+            } else {
+                method.append(inputRpcName.charAt(i));
                 makeItUpperCase = false;
             }
         }
-        return method;
+        return method.toString();
     }
 
+    private enum modeT {
+        SYNCH,
+        ASYNCH
+    }
 }