Fixing sonar bugs in package ..auth.clieditor 27/55527/4
authorDinh Danh Le <dinh.danh.le@ericsson.com>
Thu, 28 Jun 2018 11:05:08 +0000 (12:05 +0100)
committerDinh Danh Le <dinh.danh.le@ericsson.com>
Thu, 28 Jun 2018 16:48:24 +0000 (17:48 +0100)
Change-Id: Ie0aa788ef9ea4e574c65928787c9be2ef72a6a61
Issue-ID: POLICY-862
Signed-off-by: Dinh Danh Le <dinh.danh.le@ericsson.com>
auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexCLIEditorMain.java
auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/ApexModelHandler.java
auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLILineParser.java
auth/cli-editor/src/main/java/org/onap/policy/apex/auth/clieditor/CLIParameters.java
plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJMSConsumer.java
plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJMSProducer.java

index 0d36d2d..e484ff0 100644 (file)
@@ -56,7 +56,7 @@ public class ApexCLIEditorMain {
      * @param args the command line arguments
      */
     public ApexCLIEditorMain(final String[] args) {
-        LOGGER.info("Starting Apex CLI editor " + Arrays.toString(args) + " . . .");
+        LOGGER.info("Starting Apex CLI editor {} . . .", Arrays.toString(args));
 
         try {
             final CLIParameterParser parser = new CLIParameterParser();
@@ -73,27 +73,27 @@ public class ApexCLIEditorMain {
             return;
         }
 
-        LOGGER.debug("parameters are: " + parameters.toString());
+        LOGGER.debug("parameters are: {}", parameters.toString());
 
         // Read the command definitions
         try {
             commands = new JSONHandler<CLICommands>().read(CLICommands.class, parameters.getMetadataStream());
         } catch (final Exception e) {
-            LOGGER.error("start of Apex command line editor failed, error reading command metadata from "
-                    parameters.getMetadataLocation(), e);
+            LOGGER.error("start of Apex command line editor failed, error reading command metadata from {}",
+                    parameters.getMetadataLocation(), e);
             errorCount++;
             return;
         }
 
         // The JSON processing returns null if there is an empty file
         if (commands == null || commands.getCommandSet().isEmpty()) {
-            LOGGER.error("start of Apex command line editor failed, no commands found in "
-                    parameters.getApexPropertiesLocation());
+            LOGGER.error("start of Apex command line editor failed, no commands found in {}",
+                    parameters.getApexPropertiesLocation());
             errorCount++;
             return;
         }
 
-        LOGGER.debug("found " + commands.getCommandSet().size() + " commands");
+        LOGGER.debug("found {} commands", commands.getCommandSet().size());
 
         // Read the Apex properties
         try {
@@ -109,13 +109,13 @@ public class ApexCLIEditorMain {
 
         // The JSON processing returns null if there is an empty file
         if (apexModelProperties == null) {
-            LOGGER.error("start of Apex command line editor failed, no Apex model properties found in "
-                    parameters.getApexPropertiesLocation());
+            LOGGER.error("start of Apex command line editor failed, no Apex model properties found in {}",
+                    parameters.getApexPropertiesLocation());
             errorCount++;
             return;
         }
 
-        LOGGER.debug("model properties are: " + apexModelProperties.toString());
+        LOGGER.debug("model properties are: {}", apexModelProperties.toString());
 
         // Find the system commands
         final Set<KeywordNode> systemCommandNodes = new TreeSet<>();
@@ -152,12 +152,10 @@ public class ApexCLIEditorMain {
             if (errorCount == 0) {
                 LOGGER.info("Apex CLI editor completed execution");
             } else {
-                LOGGER.error("execution of Apex command line editor failed: " + errorCount
-                        + " command execution failure(s) occurred");
+                LOGGER.error("execution of Apex command line editor failed: {} command execution failure(s) occurred", errorCount);
             }
         } catch (final IOException e) {
             LOGGER.error("execution of Apex command line editor failed: " + e.getMessage());
-            return;
         }
     }
 
index a5e5302..bfa2239 100644 (file)
@@ -36,6 +36,8 @@ import org.onap.policy.apex.model.modelapi.ApexModelFactory;
  * @author Liam Fallon (liam.fallon@ericsson.com)
  */
 public class ApexModelHandler {
+    private static final String FAILED_FOR_COMMAND = "\" failed for command \"";
+    private static final String INVOCATION_OF_SPECIFIED_METHOD = "invocation of specified method \"";
     private ApexModel apexModel = null;
 
     /**
@@ -91,21 +93,21 @@ public class ApexModelHandler {
                 return result;
             } else {
                 throw new CLIException(
-                        "invocation of specified method \"" + command.getApiMethod() + "\" failed for command \""
+                        INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND
                                 + command.getName() + "\" the returned object is not an instance of ApexAPIResult");
             }
         } catch (IllegalAccessException | IllegalArgumentException e) {
-            writer.println("invocation of specified method \"" + command.getApiMethod() + "\" failed for command \""
+            writer.println(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND
                     + command.getName() + "\"");
             e.printStackTrace(writer);
-            throw new CLIException("invocation of specified method \"" + command.getApiMethod()
-                    + "\" failed for command \"" + command.getName() + "\"", e);
+            throw new CLIException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod()
+                    + FAILED_FOR_COMMAND + command.getName() + "\"", e);
         } catch (final InvocationTargetException e) {
-            writer.println("invocation of specified method \"" + command.getApiMethod() + "\" failed for command \""
+            writer.println(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod() + FAILED_FOR_COMMAND
                     + command.getName() + "\"");
             e.getCause().printStackTrace(writer);
-            throw new CLIException("invocation of specified method \"" + command.getApiMethod()
-                    + "\" failed for command \"" + command.getName() + "\"", e);
+            throw new CLIException(INVOCATION_OF_SPECIFIED_METHOD + command.getApiMethod()
+                    + FAILED_FOR_COMMAND + command.getName() + "\"", e);
         }
     }
 
@@ -153,7 +155,7 @@ public class ApexModelHandler {
                         argumentValues.get(command.getArgumentList().get(i).getArgumentName()).getValue();
 
                 if (parametertype.equals(boolean.class)) {
-                    parameterArray[i] = (boolean) Boolean.valueOf(parameterValue);
+                    parameterArray[i] = Boolean.valueOf(parameterValue);
                 } else {
                     parameterArray[i] = parameterValue;
                 }
index 502eb48..bbeface 100644 (file)
@@ -80,17 +80,18 @@ public class CLILineParser {
 
         for (int i = 0; i < wordsSplitOnQuotes.size();) {
             if ("\"".equals(wordsSplitOnQuotes.get(i))) {
-                String quotedWord = wordsSplitOnQuotes.get(i++);
+                StringBuilder quotedWord = new StringBuilder(wordsSplitOnQuotes.get(i++));
 
                 for (; i < wordsSplitOnQuotes.size(); i++) {
-                    quotedWord += wordsSplitOnQuotes.get(i);
+                    quotedWord.append(wordsSplitOnQuotes.get(i));
                     if ("\"".equals(wordsSplitOnQuotes.get(i))) {
                         i++;
                         break;
                     }
                 }
-                if (quotedWord.matches("^\".*\"$")) {
-                    wordsWithQuotesMerged.add(quotedWord);
+                String quotedWordToString = quotedWord.toString();
+                if (quotedWordToString.matches("^\".*\"$")) {
+                    wordsWithQuotesMerged.add(quotedWordToString);
                 } else {
                     throw new CLIException("trailing quote found in input " + wordsSplitOnQuotes);
                 }
@@ -274,7 +275,7 @@ public class CLILineParser {
      */
     private ArrayList<String> checkFormat(final ArrayList<String> commandWords, final String logicBlock) {
         // There should be at least one word
-        if (commandWords.size() == 0) {
+        if (commandWords.isEmpty()) {
             return commandWords;
         }
 
index 5f363cf..3ea39dd 100644 (file)
@@ -159,8 +159,7 @@ public class CLIParameters {
      * @throws IOException the IO exception
      */
     public OutputStream getOutputStream() throws IOException {
-        // Check if log suppression is active, if so, consume all output on a byte array output
-        // stream
+        // Check if log suppression is active, if so, consume all output on a byte array output stream
         if (isSuppressLogSet()) {
             return new ByteArrayOutputStream();
 
@@ -183,14 +182,16 @@ public class CLIParameters {
             return;
         }
         final File theFile = new File(fileName);
+        final String prefixExceptionMessage = "File " + fileName + "of type " + fileTag;
+
         if (!theFile.exists()) {
-            throw new CLIException("file " + fileName + " of type " + fileTag + " does not exist");
+            throw new CLIException(prefixExceptionMessage + " does not exist");
         }
         if (!theFile.isFile()) {
-            throw new CLIException("file " + fileName + " of type " + fileTag + " is not a normal file");
+            throw new CLIException(prefixExceptionMessage + " is not a normal file");
         }
         if (!theFile.canRead()) {
-            throw new CLIException("file " + fileName + " of type " + fileTag + " is ureadable");
+            throw new CLIException(prefixExceptionMessage + " is ureadable");
         }
     }
 
@@ -205,18 +206,19 @@ public class CLIParameters {
             return;
         }
         final File theFile = new File(fileName);
+        final String prefixExceptionMessage = "File " + fileName + "of type " + fileTag;
         if (theFile.exists()) {
             if (!theFile.isFile()) {
-                throw new CLIException("file " + fileName + " of type " + fileTag + " is not a normal file");
+                throw new CLIException(prefixExceptionMessage + " is not a normal file");
             }
             if (!theFile.canWrite()) {
-                throw new CLIException("file " + fileName + " of type " + fileTag + " cannot be written");
+                throw new CLIException(prefixExceptionMessage + " cannot be written");
             }
         } else {
             try {
                 theFile.createNewFile();
             } catch (final IOException e) {
-                throw new CLIException("file " + fileName + " cannot be created: ", e);
+                throw new CLIException(prefixExceptionMessage + " cannot be created: ", e);
             }
         }
     }
@@ -232,14 +234,14 @@ public class CLIParameters {
             return;
         }
         final File theDirectory = new File(directoryName);
+        final String prefixExceptionMessage = "directory " + directoryName + "of type " + directoryTag;
+
         if (theDirectory.exists()) {
             if (!theDirectory.isDirectory()) {
-                throw new CLIException(
-                        "directory " + directoryName + " of type " + directoryTag + " is not a directory");
+                throw new CLIException(prefixExceptionMessage + " is not a directory");
             }
             if (!theDirectory.canWrite()) {
-                throw new CLIException(
-                        "directory " + directoryName + " of type " + directoryTag + " cannot be written");
+                throw new CLIException(prefixExceptionMessage + " cannot be written");
             }
         }
     }
index 745a1e9..a965175 100644 (file)
@@ -196,53 +196,37 @@ public class ApexJMSConsumer implements MessageListener, ApexEventConsumer, Runn
     @Override
     public void run() {
         // JMS session and message consumer for receiving messages
-        Session jmsSession = null;
-        MessageConsumer messageConsumer = null;
-
-        // Create a session to the JMS server
-        try {
-            jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
+        try (Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE)) {
+            // Create a message consumer for reception of messages and set this class as a message listener
+            createMessageConsumer(jmsSession);
         } catch (final Exception e) {
             final String errorMessage = "failed to create a JMS session towards the JMS server for receiving messages";
             LOGGER.warn(errorMessage, e);
             throw new ApexEventRuntimeException(errorMessage, e);
         }
-
-        // Create a message consumer for reception of messages and set this class as a message listener
-        try {
-            messageConsumer = jmsSession.createConsumer(jmsIncomingTopic);
-            messageConsumer.setMessageListener(this);
-        } catch (final Exception e) {
-            final String errorMessage = "failed to create a JMS message consumer for receiving messages";
-            LOGGER.warn(errorMessage, e);
-            throw new ApexEventRuntimeException(errorMessage, e);
-        }
-
         // Everything is now set up
         if (LOGGER.isDebugEnabled()) {
             LOGGER.debug("event receiver " + this.getClass().getName() + ":" + this.name + " subscribed to JMS topic: "
                     + jmsConsumerProperties.getConsumerTopic());
         }
-
         // The endless loop that receives events over JMS
         while (consumerThread.isAlive() && !stopOrderedFlag) {
             ThreadUtilities.sleep(jmsConsumerProperties.getConsumerWaitTime());
         }
+    }
 
-        // Close the message consumer
-        try {
-            messageConsumer.close();
-        } catch (final Exception e) {
-            final String errorMessage = "failed to close the JMS message consumer for receiving messages";
-            LOGGER.warn(errorMessage, e);
-        }
-
-        // Close the session
-        try {
-            jmsSession.close();
+    /**
+     * The helper function to create a message consumer from a given JMS session
+     * 
+     * @param jmsSession a JMS session
+     */
+    private void createMessageConsumer(Session jmsSession) {
+        try (MessageConsumer messageConsumer = jmsSession.createConsumer(jmsIncomingTopic)) {
+            messageConsumer.setMessageListener(this);
         } catch (final Exception e) {
-            final String errorMessage = "failed to close the JMS session for receiving messages";
+            final String errorMessage = "failed to create a JMS message consumer for receiving messages";
             LOGGER.warn(errorMessage, e);
+            throw new ApexEventRuntimeException(errorMessage, e);
         }
     }
 
index 017f07f..edf7863 100644 (file)
@@ -86,9 +86,9 @@ public class ApexJMSProducer implements ApexEventProducer {
 
         // Check and get the JMS Properties
         if (!(producerParameters.getCarrierTechnologyParameters() instanceof JMSCarrierTechnologyParameters)) {
-            LOGGER.warn("specified producer properties are not applicable to a JMS producer (" + this.name + ")");
-            throw new ApexEventException(
-                    "specified producer properties are not applicable to a JMS producer (" + this.name + ")");
+            final String errorMessage = "specified producer properties are not applicable to a JMS producer (" + this.name + ")";
+            LOGGER.warn(errorMessage);
+            throw new ApexEventException(errorMessage);
         }
         jmsProducerProperties = (JMSCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters();