Refactor ApiCommandLineArguments class 55/120555/2
authoradheli.tavares <adheli.tavares@est.tech>
Tue, 13 Apr 2021 15:38:04 +0000 (16:38 +0100)
committeradheli.tavares <adheli.tavares@est.tech>
Fri, 16 Apr 2021 09:47:03 +0000 (10:47 +0100)
CMD Class to use CMD Handler from Common.

Issue-ID: POLICY-3129
Change-Id: I7a1b960b1e3ecc6df0f7dde6b3301d640f4feb11
Signed-off-by: adheli.tavares <adheli.tavares@est.tech>
main/src/main/java/org/onap/policy/api/main/startstop/ApiCommandLineArguments.java
main/src/main/java/org/onap/policy/api/main/startstop/Main.java
main/src/test/java/org/onap/policy/api/main/parameters/TestApiParameterHandler.java
main/src/test/java/org/onap/policy/api/main/startstop/TestApiCommandLineArguments.java

index 8073f7c..47f004e 100644 (file)
@@ -1,6 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
+ *  Modifications Copyright (C) 2021 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 
 package org.onap.policy.api.main.startstop;
 
-import java.io.File;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.net.URL;
-import java.util.Arrays;
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.DefaultParser;
-import org.apache.commons.cli.HelpFormatter;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.onap.policy.api.main.exception.PolicyApiException;
 import org.onap.policy.api.main.exception.PolicyApiRuntimeException;
-import org.onap.policy.common.utils.resources.ResourceUtils;
+import org.onap.policy.common.utils.cmd.CommandLineArgumentsHandler;
+import org.onap.policy.common.utils.cmd.CommandLineException;
+import org.onap.policy.common.utils.resources.MessageConstants;
 
 /**
  * This class reads and handles command line parameters for the policy api main program.
  */
-public class ApiCommandLineArguments {
-    private static final String FILE_MESSAGE_PREAMBLE = " file \"";
-    private static final int HELP_LINE_LENGTH = 120;
-
-    // Apache Commons CLI options
-    private final Options options;
-
-    // The command line options
-    private String configurationFilePath = null;
+public class ApiCommandLineArguments extends CommandLineArgumentsHandler {
 
     /**
-     * Construct the options for the CLI editor.
+     * Construct the options for the CLI editor from super.
      */
     public ApiCommandLineArguments() {
-        //@formatter:off
-        options = new Options();
-        options.addOption(Option.builder("h")
-                .longOpt("help")
-                .desc("outputs the usage of this command")
-                .required(false)
-                .type(Boolean.class)
-                .build());
-        options.addOption(Option.builder("v")
-                .longOpt("version")
-                .desc("outputs the version of policy api")
-                .required(false)
-                .type(Boolean.class)
-                .build());
-        options.addOption(Option.builder("c")
-                .longOpt("config-file")
-                .desc("the full path to the configuration file to use, "
-                        + "the configuration file must be a Json file containing the policy api parameters")
-                .hasArg()
-                .argName("CONFIG_FILE")
-                .required(false)
-                .type(String.class)
-                .build());
-        //@formatter:on
+        super(Main.class.getName(), MessageConstants.POLICY_API);
     }
 
     /**
@@ -84,154 +44,12 @@ public class ApiCommandLineArguments {
      * @param args The command line arguments
      */
     public ApiCommandLineArguments(final String[] args) {
-        // Set up the options with the default constructor
         this();
 
-        // Parse the arguments
         try {
             parse(args);
-        } catch (final PolicyApiException e) {
+        } catch (final CommandLineException e) {
             throw new PolicyApiRuntimeException("parse error on policy api parameters", e);
         }
     }
-
-    /**
-     * Parse the command line options.
-     *
-     * @param args The command line arguments
-     * @return a string with a message for help and version, or null if there is no message
-     * @throws PolicyApiException on command argument errors
-     */
-    public String parse(final String[] args) throws PolicyApiException {
-        // Clear all our arguments
-        setConfigurationFilePath(null);
-
-        CommandLine commandLine = null;
-        try {
-            commandLine = new DefaultParser().parse(options, args);
-        } catch (final ParseException e) {
-            throw new PolicyApiException("invalid command line arguments specified : " + e.getMessage());
-        }
-
-        // Arguments left over after Commons CLI does its stuff
-        final String[] remainingArgs = commandLine.getArgs();
-
-        if (remainingArgs.length > 0 && commandLine.hasOption('c') || remainingArgs.length > 0) {
-            throw new PolicyApiException("too many command line arguments specified : " + Arrays.toString(args));
-        }
-
-        if (remainingArgs.length == 1) {
-            configurationFilePath = remainingArgs[0];
-        }
-
-        if (commandLine.hasOption('h')) {
-            return help(Main.class.getName());
-        }
-
-        if (commandLine.hasOption('v')) {
-            return version();
-        }
-
-        if (commandLine.hasOption('c')) {
-            setConfigurationFilePath(commandLine.getOptionValue('c'));
-        }
-
-        return null;
-    }
-
-    /**
-     * Validate the command line options.
-     *
-     * @throws PolicyApiException on command argument validation errors
-     */
-    public void validate() throws PolicyApiException {
-        validateReadableFile("policy api configuration", configurationFilePath);
-    }
-
-    /**
-     * Print version information for policy api.
-     *
-     * @return the version string
-     */
-    public String version() {
-        return ResourceUtils.getResourceAsString("version.txt");
-    }
-
-    /**
-     * Print help information for policy api.
-     *
-     * @param mainClassName the main class name
-     * @return the help string
-     */
-    public String help(final String mainClassName) {
-        final HelpFormatter helpFormatter = new HelpFormatter();
-        final StringWriter stringWriter = new StringWriter();
-        final PrintWriter printWriter = new PrintWriter(stringWriter);
-
-        helpFormatter.printHelp(printWriter, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, 0,
-                0, "");
-
-        return stringWriter.toString();
-    }
-
-    /**
-     * Gets the configuration file path.
-     *
-     * @return the configuration file path
-     */
-    public String getConfigurationFilePath() {
-        return configurationFilePath;
-    }
-
-    /**
-     * Gets the full expanded configuration file path.
-     *
-     * @return the configuration file path
-     */
-    public String getFullConfigurationFilePath() {
-        return ResourceUtils.getFilePath4Resource(getConfigurationFilePath());
-    }
-
-    /**
-     * Sets the configuration file path.
-     *
-     * @param configurationFilePath the configuration file path
-     */
-    public void setConfigurationFilePath(final String configurationFilePath) {
-        this.configurationFilePath = configurationFilePath;
-
-    }
-
-    /**
-     * Check set configuration file path.
-     *
-     * @return true, if check set configuration file path
-     */
-    public boolean checkSetConfigurationFilePath() {
-        return configurationFilePath != null && configurationFilePath.length() > 0;
-    }
-
-    /**
-     * Validate readable file.
-     *
-     * @param fileTag the file tag
-     * @param fileName the file name
-     * @throws PolicyApiException on the file name passed as a parameter
-     */
-    private void validateReadableFile(final String fileTag, final String fileName) throws PolicyApiException {
-        if (fileName == null || fileName.length() == 0) {
-            throw new PolicyApiException(fileTag + " file was not specified as an argument");
-        }
-
-        // The file name refers to a resource on the local file system
-        final URL fileUrl = ResourceUtils.getUrl4Resource(fileName);
-        if (fileUrl == null) {
-            throw new PolicyApiException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
-        }
-
-        final File theFile = new File(fileUrl.getPath());
-        if (!theFile.exists()) {
-            throw new PolicyApiException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist");
-        }
-    }
 }
index c8bce6f..36734f3 100644 (file)
@@ -5,6 +5,7 @@
  * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2020 Bell Canada. All rights reserved.
+ * Modifications Copyright (C) 2021 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -29,6 +30,7 @@ import org.onap.policy.api.main.exception.PolicyApiException;
 import org.onap.policy.api.main.exception.PolicyApiRuntimeException;
 import org.onap.policy.api.main.parameters.ApiParameterGroup;
 import org.onap.policy.api.main.parameters.ApiParameterHandler;
+import org.onap.policy.common.utils.cmd.CommandLineException;
 import org.onap.policy.common.utils.resources.MessageConstants;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -79,7 +81,7 @@ public class Main {
 
             // Start the activator
             activator.initialize();
-        } catch (final PolicyApiException e) {
+        } catch (final PolicyApiException | CommandLineException e) {
             throw new PolicyApiRuntimeException(
                 String.format(MessageConstants.START_FAILURE_MSG, MessageConstants.POLICY_API), e);
         }
index 3437908..5e1b7eb 100644 (file)
@@ -2,6 +2,7 @@
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
  *  Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ *  Modifications Copyright (C) 2021 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -31,6 +32,7 @@ import java.nio.file.Paths;
 import org.junit.Test;
 import org.onap.policy.api.main.exception.PolicyApiException;
 import org.onap.policy.api.main.startstop.ApiCommandLineArguments;
+import org.onap.policy.common.utils.cmd.CommandLineException;
 
 /**
  * Class to perform unit test of ApiParameterHandler.
@@ -38,7 +40,7 @@ import org.onap.policy.api.main.startstop.ApiCommandLineArguments;
  */
 public class TestApiParameterHandler {
     @Test
-    public void testParameterHandlerNoParameterFile() throws PolicyApiException {
+    public void testParameterHandlerNoParameterFile() throws PolicyApiException, CommandLineException {
         final String[] noArgumentString = {"-c", "parameters/NoParameterFile.json"};
         final ApiCommandLineArguments noArguments = new ApiCommandLineArguments();
         noArguments.parse(noArgumentString);
@@ -52,7 +54,7 @@ public class TestApiParameterHandler {
     }
 
     @Test
-    public void testParameterHandlerEmptyParameters() throws PolicyApiException {
+    public void testParameterHandlerEmptyParameters() throws PolicyApiException, CommandLineException {
         final String[] emptyArgumentString = {"-c", "parameters/EmptyParameters.json"};
         final ApiCommandLineArguments emptyArguments = new ApiCommandLineArguments();
         emptyArguments.parse(emptyArgumentString);
@@ -66,7 +68,7 @@ public class TestApiParameterHandler {
     }
 
     @Test
-    public void testParameterHandlerBadParameters() throws PolicyApiException {
+    public void testParameterHandlerBadParameters() throws PolicyApiException, CommandLineException {
         final String[] badArgumentString = {"-c", "parameters/BadParameters.json"};
         final ApiCommandLineArguments badArguments = new ApiCommandLineArguments();
         badArguments.parse(badArgumentString);
@@ -82,7 +84,7 @@ public class TestApiParameterHandler {
     }
 
     @Test
-    public void testParameterHandlerInvalidParameters() throws PolicyApiException {
+    public void testParameterHandlerInvalidParameters() throws PolicyApiException, CommandLineException {
         final String[] invalidArgumentString = {"-c", "parameters/InvalidParameters.json"};
         final ApiCommandLineArguments invalidArguments = new ApiCommandLineArguments();
         invalidArguments.parse(invalidArgumentString);
@@ -98,7 +100,7 @@ public class TestApiParameterHandler {
     }
 
     @Test
-    public void testParameterHandlerNoParameters() throws PolicyApiException {
+    public void testParameterHandlerNoParameters() throws PolicyApiException, CommandLineException {
         final String[] noArgumentString = {"-c", "parameters/NoParameters.json"};
         final ApiCommandLineArguments noArguments = new ApiCommandLineArguments();
         noArguments.parse(noArgumentString);
@@ -116,7 +118,7 @@ public class TestApiParameterHandler {
     }
 
     @Test
-    public void testParameterHandlerMinumumParameters() throws PolicyApiException {
+    public void testParameterHandlerMinumumParameters() throws PolicyApiException, CommandLineException {
         final String[] minArgumentString = {"-c", "parameters/MinimumParameters.json"};
         final ApiCommandLineArguments minArguments = new ApiCommandLineArguments();
         minArguments.parse(minArgumentString);
@@ -125,7 +127,7 @@ public class TestApiParameterHandler {
     }
 
     @Test
-    public void testApiParameterGroup() throws PolicyApiException {
+    public void testApiParameterGroup() throws PolicyApiException, CommandLineException {
         final String[] apiConfigParameters = {"-c", "parameters/ApiConfigParameters_Https.json"};
         final ApiCommandLineArguments arguments = new ApiCommandLineArguments();
         arguments.parse(apiConfigParameters);
@@ -135,7 +137,7 @@ public class TestApiParameterHandler {
     }
 
     @Test
-    public void testApiParameterGroup_InvalidName() throws PolicyApiException {
+    public void testApiParameterGroup_InvalidName() throws PolicyApiException, CommandLineException {
         final String[] apiConfigParameters = {"-c", "parameters/ApiConfigParameters_InvalidName.json"};
         final ApiCommandLineArguments arguments = new ApiCommandLineArguments();
         arguments.parse(apiConfigParameters);
@@ -150,7 +152,8 @@ public class TestApiParameterHandler {
     }
 
     @Test
-    public void testApiParameterGroup_InvalidRestServerParameters() throws PolicyApiException, IOException {
+    public void testApiParameterGroup_InvalidRestServerParameters()
+            throws PolicyApiException, IOException, CommandLineException {
         final String[] apiConfigParameters = {"-c", "parameters/ApiConfigParameters_InvalidRestServerParameters.json"};
         final ApiCommandLineArguments arguments = new ApiCommandLineArguments();
         arguments.parse(apiConfigParameters);
@@ -167,7 +170,7 @@ public class TestApiParameterHandler {
     }
 
     @Test
-    public void testApiVersion() throws PolicyApiException {
+    public void testApiVersion() throws PolicyApiException, CommandLineException {
         final String[] apiConfigParameters = {"-v"};
         final ApiCommandLineArguments arguments = new ApiCommandLineArguments();
         final String version = arguments.parse(apiConfigParameters);
@@ -175,7 +178,7 @@ public class TestApiParameterHandler {
     }
 
     @Test
-    public void testApiHelp() throws PolicyApiException {
+    public void testApiHelp() throws PolicyApiException, CommandLineException {
         final String[] apiConfigParameters = {"-h"};
         final ApiCommandLineArguments arguments = new ApiCommandLineArguments();
         final String help = arguments.parse(apiConfigParameters);
index 8adfacc..8d3c42c 100644 (file)
@@ -3,6 +3,7 @@
  * ONAP Policy API
  * ================================================================================
  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2021 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 
 package org.onap.policy.api.main.startstop;
 
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
 import org.junit.Test;
-import org.onap.policy.api.main.exception.PolicyApiException;
 import org.onap.policy.api.main.exception.PolicyApiRuntimeException;
 
 public class TestApiCommandLineArguments {
@@ -33,38 +34,35 @@ public class TestApiCommandLineArguments {
 
     @Test(expected = PolicyApiRuntimeException.class)
     public void testApiCommandLineArgumentsStringArray() {
-        String [] args = {"---d"};
+        String[] args = {"---d"};
         new ApiCommandLineArguments(args);
     }
 
     @Test
     public void testNonExistentFileValidateReadableFile() {
         apiCmdArgs.setConfigurationFilePath("src/test/resources/filetest/nonexist.json ");
-        assertThatThrownBy(
-                apiCmdArgs::validate
-            )
-            .isInstanceOf(PolicyApiException.class)
-            .hasMessageContaining("file \"src/test/resources/filetest/nonexist.json \" does not exist");
+        assertThatThrownBy(apiCmdArgs::validate)
+                .hasMessageContaining("file \"src/test/resources/filetest/nonexist.json \" does not exist");
     }
 
     @Test
     public void testEmptyFileNameValidateReadableFile() {
         apiCmdArgs.setConfigurationFilePath("");
-        assertThatThrownBy(
-                 apiCmdArgs::validate
-            )
-            .isInstanceOf(PolicyApiException.class)
-            .hasMessageContaining("policy api configuration file was not specified as an argument");
+        assertThatThrownBy(apiCmdArgs::validate)
+                .hasMessageContaining("policy-api configuration file was not specified as an argument");
     }
 
     @Test
     public void testInvalidUrlValidateReadableFile() {
         apiCmdArgs.setConfigurationFilePath("src/test\\resources/filetest\\n");
-        assertThatThrownBy(
-                apiCmdArgs::validate
-            )
-            .isInstanceOf(PolicyApiException.class)
-            .hasMessageContaining(
-                    "policy api configuration file \"src/test\\resources/filetest\\n\" does not exist");
+        assertThatThrownBy(apiCmdArgs::validate).hasMessageContaining(
+                "policy-api configuration file \"src/test\\resources/filetest\\n\" does not exist");
+    }
+
+    @Test
+    public void testVersion() {
+        String[] testArgs = {"-v"};
+        ApiCommandLineArguments cmdArgs = new ApiCommandLineArguments(testArgs);
+        assertThat(cmdArgs.version()).startsWith("ONAP Policy Framework Api Service");
     }
 }