From 07b7ba00a053a26a5eef39070bff5297c630c5ce Mon Sep 17 00:00:00 2001 From: ramverma Date: Thu, 31 Jan 2019 13:09:00 +0000 Subject: Create basic structure of pap component 1) Creating the basic code structure of pap component which includes main sub-module having Main, PapActivator, PapCommandLineArguments, PapParameterGroup & PapParameterHandler. Along with few exception classes. Basicalliy the structure follows the pattern developed in policy/distribution component. 2) Created the related unit test cases and required test resources. Change-Id: I67c82f9d072e6c8a306cb983accb693da70e58a2 Issue-ID: POLICY-1476 Signed-off-by: ramverma --- .../onap/policy/pap/main/PolicyPapException.java | 49 +++++ .../policy/pap/main/PolicyPapRuntimeException.java | 49 +++++ .../pap/main/parameters/PapParameterGroup.java | 78 +++++++ .../pap/main/parameters/PapParameterHandler.java | 85 +++++++ .../org/onap/policy/pap/main/startstop/Main.java | 143 ++++++++++++ .../policy/pap/main/startstop/PapActivator.java | 130 +++++++++++ .../main/startstop/PapCommandLineArguments.java | 244 +++++++++++++++++++++ main/src/main/resources/version.txt | 4 + .../org/onap/policy/pap/main/TestExceptions.java | 44 ++++ .../policy/pap/main/parameters/CommonTestData.java | 32 +++ .../pap/main/parameters/TestPapParameterGroup.java | 73 ++++++ .../main/parameters/TestPapParameterHandler.java | 166 ++++++++++++++ .../onap/policy/pap/main/startstop/TestMain.java | 72 ++++++ .../pap/main/startstop/TestPapActivator.java | 54 +++++ .../test/resources/parameters/EmptyParameters.json | 0 .../resources/parameters/InvalidParameters.json | 3 + .../resources/parameters/MinimumParameters.json | 3 + .../test/resources/parameters/NoParameters.json | 2 + .../resources/parameters/PapConfigParameters.json | 3 + .../PapConfigParameters_InvalidName.json | 3 + 20 files changed, 1237 insertions(+) create mode 100644 main/src/main/java/org/onap/policy/pap/main/PolicyPapException.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/PolicyPapRuntimeException.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterHandler.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/startstop/Main.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java create mode 100644 main/src/main/java/org/onap/policy/pap/main/startstop/PapCommandLineArguments.java create mode 100644 main/src/main/resources/version.txt create mode 100644 main/src/test/java/org/onap/policy/pap/main/TestExceptions.java create mode 100644 main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java create mode 100644 main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java create mode 100644 main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java create mode 100644 main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java create mode 100644 main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java create mode 100644 main/src/test/resources/parameters/EmptyParameters.json create mode 100644 main/src/test/resources/parameters/InvalidParameters.json create mode 100644 main/src/test/resources/parameters/MinimumParameters.json create mode 100644 main/src/test/resources/parameters/NoParameters.json create mode 100644 main/src/test/resources/parameters/PapConfigParameters.json create mode 100644 main/src/test/resources/parameters/PapConfigParameters_InvalidName.json (limited to 'main/src') diff --git a/main/src/main/java/org/onap/policy/pap/main/PolicyPapException.java b/main/src/main/java/org/onap/policy/pap/main/PolicyPapException.java new file mode 100644 index 00000000..6459d6bb --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/PolicyPapException.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main; + +/** + * This exception will be called if an error occurs in policy pap service. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class PolicyPapException extends Exception { + private static final long serialVersionUID = -8507246953751956974L; + + /** + * Instantiates a new policy pap exception with a message. + * + * @param message the message + */ + public PolicyPapException(final String message) { + super(message); + } + + /** + * Instantiates a new policy pap exception with a message and a caused by exception. + * + * @param message the message + * @param exp the exception that caused this exception to be thrown + */ + public PolicyPapException(final String message, final Exception exp) { + super(message, exp); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/PolicyPapRuntimeException.java b/main/src/main/java/org/onap/policy/pap/main/PolicyPapRuntimeException.java new file mode 100644 index 00000000..e1df1b16 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/PolicyPapRuntimeException.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main; + +/** + * This runtime exception will be called if a runtime error occurs when using policy pap. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class PolicyPapRuntimeException extends RuntimeException { + private static final long serialVersionUID = -8507246953751956974L; + + /** + * Instantiates a new policy pap runtime exception with a message. + * + * @param message the message + */ + public PolicyPapRuntimeException(final String message) { + super(message); + } + + /** + * Instantiates a new policy pap runtime exception with a message and a caused by exception. + * + * @param message the message + * @param exp the exception that caused this exception to be thrown + */ + public PolicyPapRuntimeException(final String message, final Exception exp) { + super(message, exp); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java b/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java new file mode 100644 index 00000000..01032c56 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.parameters; + +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.parameters.ValidationStatus; +import org.onap.policy.common.utils.validation.ParameterValidationUtils; + +/** + * Class to hold all parameters needed for pap component. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class PapParameterGroup implements ParameterGroup { + private String name; + + /** + * Create the pap parameter group. + * + * @param name the parameter group name + */ + public PapParameterGroup(final String name) { + this.name = name; + } + + /** + * Return the name of this parameter group instance. + * + * @return name the parameter group name + */ + @Override + public String getName() { + return name; + } + + /** + * Set the name of this parameter group instance. + * + * @param name the parameter group name + */ + @Override + public void setName(final String name) { + this.name = name; + } + + /** + * Validate the parameter group. + * + * @return the result of the validation + */ + @Override + public GroupValidationResult validate() { + final GroupValidationResult validationResult = new GroupValidationResult(this); + if (!ParameterValidationUtils.validateStringParameter(name)) { + validationResult.setResult("name", ValidationStatus.INVALID, "must be a non-blank string"); + } + return validationResult; + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterHandler.java b/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterHandler.java new file mode 100644 index 00000000..f397daed --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterHandler.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.parameters; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.io.FileReader; + +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.startstop.PapCommandLineArguments; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class handles reading, parsing and validating of policy pap parameters from JSON files. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class PapParameterHandler { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(PapParameterHandler.class); + + /** + * Read the parameters from the parameter file. + * + * @param arguments the arguments passed to policy pap + * @return the parameters read from the configuration file + * @throws PolicyPapException on parameter exceptions + */ + public PapParameterGroup getParameters(final PapCommandLineArguments arguments) throws PolicyPapException { + PapParameterGroup papParameterGroup = null; + + // Read the parameters + try { + // Read the parameters from JSON using Gson + final Gson gson = new GsonBuilder().create(); + papParameterGroup = + gson.fromJson(new FileReader(arguments.getFullConfigurationFilePath()), PapParameterGroup.class); + } catch (final Exception e) { + final String errorMessage = "error reading parameters from \"" + arguments.getConfigurationFilePath() + + "\"\n" + "(" + e.getClass().getSimpleName() + "):" + e.getMessage(); + LOGGER.error(errorMessage, e); + throw new PolicyPapException(errorMessage, e); + } + + // The JSON processing returns null if there is an empty file + if (papParameterGroup == null) { + final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\""; + LOGGER.error(errorMessage); + throw new PolicyPapException(errorMessage); + } + + // validate the parameters + final GroupValidationResult validationResult = papParameterGroup.validate(); + if (!validationResult.isValid()) { + String returnMessage = + "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n"; + returnMessage += validationResult.getResult(); + + LOGGER.error(returnMessage); + throw new PolicyPapException(returnMessage); + } + + return papParameterGroup; + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/Main.java b/main/src/main/java/org/onap/policy/pap/main/startstop/Main.java new file mode 100644 index 00000000..63d41a02 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/startstop/Main.java @@ -0,0 +1,143 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.startstop; + +import java.util.Arrays; + +import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.parameters.PapParameterGroup; +import org.onap.policy.pap.main.parameters.PapParameterHandler; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class initiates ONAP Policy Framework PAP component. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class Main { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(Main.class); + + private PapActivator activator; + private PapParameterGroup parameterGroup; + + /** + * Instantiates the policy pap service. + * + * @param args the command line arguments + */ + public Main(final String[] args) { + final String argumentString = Arrays.toString(args); + LOGGER.info("Starting policy pap service with arguments - {}", argumentString); + + // Check the arguments + final PapCommandLineArguments arguments = new PapCommandLineArguments(); + try { + // The arguments return a string if there is a message to print and we should exit + final String argumentMessage = arguments.parse(args); + if (argumentMessage != null) { + LOGGER.info(argumentMessage); + return; + } + // Validate that the arguments are sane + arguments.validate(); + } catch (final PolicyPapException e) { + LOGGER.error("start of policy pap service failed", e); + return; + } + + // Read the parameters + try { + parameterGroup = new PapParameterHandler().getParameters(arguments); + } catch (final Exception e) { + LOGGER.error("start of policy pap service failed", e); + return; + } + + // Now, create the activator for the policy pap service + activator = new PapActivator(parameterGroup); + + // Start the activator + try { + activator.initialize(); + } catch (final PolicyPapException e) { + LOGGER.error("start of policy pap service failed, used parameters are {}", Arrays.toString(args), e); + return; + } + + // Add a shutdown hook to shut everything down in an orderly manner + Runtime.getRuntime().addShutdownHook(new PolicyPapShutdownHookClass()); + LOGGER.info("Started policy pap service"); + } + + /** + * Get the parameters specified in JSON. + * + * @return the parameters + */ + public PapParameterGroup getParameters() { + return parameterGroup; + } + + /** + * Shut down Execution. + * + * @throws PolicyPapException on shutdown errors + */ + public void shutdown() throws PolicyPapException { + // clear the parameterGroup variable + parameterGroup = null; + + // clear the pap activator + if (activator != null) { + activator.terminate(); + } + } + + /** + * The Class PolicyPapShutdownHookClass terminates the policy pap service when its run method is called. + */ + private class PolicyPapShutdownHookClass extends Thread { + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + try { + // Shutdown the policy pap service and wait for everything to stop + activator.terminate(); + } catch (final PolicyPapException e) { + LOGGER.warn("error occured during shut down of the policy pap service", e); + } + } + } + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(final String[] args) { + new Main(args); + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java b/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java new file mode 100644 index 00000000..8aec2adf --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java @@ -0,0 +1,130 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.startstop; + +import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.parameters.PapParameterGroup; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class wraps a distributor so that it can be activated as a complete service together with all its pap and + * forwarding handlers. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class PapActivator { + // The logger for this class + private static final XLogger LOGGER = XLoggerFactory.getXLogger(PapActivator.class); + + // The parameters of this policy pap activator + private final PapParameterGroup papParameterGroup; + + private static boolean alive = false; + + /** + * Instantiate the activator for policy pap as a complete service. + * + * @param papParameterGroup the parameters for the pap service + */ + public PapActivator(final PapParameterGroup papParameterGroup) { + this.papParameterGroup = papParameterGroup; + } + + /** + * Initialize pap as a complete service. + * + * @throws PolicyPapException on errors in initializing the service + */ + public void initialize() throws PolicyPapException { + try { + LOGGER.debug("Policy pap starting as a service . . ."); + registerToParameterService(papParameterGroup); + PapActivator.setAlive(true); + LOGGER.debug("Policy pap started as a service"); + } catch (final Exception exp) { + LOGGER.error("Policy pap service startup failed", exp); + throw new PolicyPapException(exp.getMessage(), exp); + } + } + + /** + * Terminate policy pap. + * + * @throws PolicyPapException on errors in terminating the service + */ + public void terminate() throws PolicyPapException { + try { + deregisterToParameterService(papParameterGroup); + PapActivator.setAlive(false); + + } catch (final Exception exp) { + LOGGER.error("Policy pap service termination failed", exp); + throw new PolicyPapException(exp.getMessage(), exp); + } + } + + /** + * Get the parameters used by the activator. + * + * @return the parameters of the activator + */ + public PapParameterGroup getParameterGroup() { + return papParameterGroup; + } + + /** + * Method to register the parameters to Common Parameter Service. + * + * @param papParameterGroup the pap parameter group + */ + public void registerToParameterService(final PapParameterGroup papParameterGroup) { + ParameterService.register(papParameterGroup); + } + + /** + * Method to deregister the parameters from Common Parameter Service. + * + * @param papParameterGroup the pap parameter group + */ + public void deregisterToParameterService(final PapParameterGroup papParameterGroup) { + ParameterService.deregister(papParameterGroup.getName()); + } + + /** + * Returns the alive status of pap service. + * + * @return the alive + */ + public static boolean isAlive() { + return alive; + } + + /** + * Change the alive status of pap service. + * + * @param status the status + */ + public static void setAlive(final boolean status) { + alive = status; + } +} diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/PapCommandLineArguments.java b/main/src/main/java/org/onap/policy/pap/main/startstop/PapCommandLineArguments.java new file mode 100644 index 00000000..4b8bc348 --- /dev/null +++ b/main/src/main/java/org/onap/policy/pap/main/startstop/PapCommandLineArguments.java @@ -0,0 +1,244 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.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.common.utils.resources.ResourceUtils; +import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.PolicyPapRuntimeException; + + +/** + * This class reads and handles command line parameters for the policy pap service. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class PapCommandLineArguments { + private static final String FILE_MESSAGE_PREAMBLE = " file \""; + private static final int HELP_LINE_LENGTH = 120; + + private final Options options; + private String configurationFilePath = null; + + /** + * Construct the options for the CLI editor. + */ + public PapCommandLineArguments() { + //@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 pap") + .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 pap parameters") + .hasArg() + .argName("CONFIG_FILE") + .required(false) + .type(String.class) + .build()); + //@formatter:on + } + + /** + * Construct the options for the CLI editor and parse in the given arguments. + * + * @param args The command line arguments + */ + public PapCommandLineArguments(final String[] args) { + // Set up the options with the default constructor + this(); + + // Parse the arguments + try { + parse(args); + } catch (final PolicyPapException e) { + throw new PolicyPapRuntimeException("parse error on policy pap 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 PolicyPapException on command argument errors + */ + public String parse(final String[] args) throws PolicyPapException { + // Clear all our arguments + setConfigurationFilePath(null); + + CommandLine commandLine = null; + try { + commandLine = new DefaultParser().parse(options, args); + } catch (final ParseException e) { + throw new PolicyPapException("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 PolicyPapException("too many command line arguments specified : " + Arrays.toString(args)); + } + + if (remainingArgs.length == 1) { + configurationFilePath = remainingArgs[0]; + } + + if (commandLine.hasOption('h')) { + return help(Main.class.getCanonicalName()); + } + + if (commandLine.hasOption('v')) { + return version(); + } + + if (commandLine.hasOption('c')) { + setConfigurationFilePath(commandLine.getOptionValue('c')); + } + + return null; + } + + /** + * Validate the command line options. + * + * @throws PolicyPapException on command argument validation errors + */ + public void validate() throws PolicyPapException { + validateReadableFile("policy pap configuration", configurationFilePath); + } + + /** + * Print version information for policy pap. + * + * @return the version string + */ + public String version() { + return ResourceUtils.getResourceAsString("version.txt"); + } + + /** + * Print help information for policy pap. + * + * @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 PolicyPapException on the file name passed as a parameter + */ + private void validateReadableFile(final String fileTag, final String fileName) throws PolicyPapException { + if (fileName == null || fileName.length() == 0) { + throw new PolicyPapException(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 PolicyPapException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); + } + + final File theFile = new File(fileUrl.getPath()); + if (!theFile.exists()) { + throw new PolicyPapException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); + } + if (!theFile.isFile()) { + throw new PolicyPapException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file"); + } + if (!theFile.canRead()) { + throw new PolicyPapException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is ureadable"); + } + } +} diff --git a/main/src/main/resources/version.txt b/main/src/main/resources/version.txt new file mode 100644 index 00000000..c691f9e1 --- /dev/null +++ b/main/src/main/resources/version.txt @@ -0,0 +1,4 @@ +ONAP Policy Framework PAP Service +Version: ${project.version} +Built (UTC): ${maven.build.timestamp} +ONAP https://wiki.onap.org \ No newline at end of file diff --git a/main/src/test/java/org/onap/policy/pap/main/TestExceptions.java b/main/src/test/java/org/onap/policy/pap/main/TestExceptions.java new file mode 100644 index 00000000..b45cdab7 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/TestExceptions.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main; + +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; + +import org.junit.Test; + +/** + * Class to perform unit test of {@link PolicyPapException PolicyPapRuntimeException}}. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class TestExceptions { + + @Test + public void test() { + assertNotNull(new PolicyPapException("Message")); + assertNotNull(new PolicyPapException("Message", new IOException())); + + assertNotNull(new PolicyPapRuntimeException("Message")); + assertNotNull(new PolicyPapRuntimeException("Message", new IOException())); + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java b/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java new file mode 100644 index 00000000..5e62ba68 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/CommonTestData.java @@ -0,0 +1,32 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.parameters; + +/** + * Class to hold/create all parameters for test cases. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class CommonTestData { + + public static final String PAP_GROUP_NAME = "PapGroup"; + +} diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java new file mode 100644 index 00000000..086d7c22 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterGroup.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.parameters; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.policy.common.parameters.GroupValidationResult; + +/** + * Class to perform unit test of {@link PapParameterGroup}. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class TestPapParameterGroup { + + @Test + public void testPapParameterGroup() { + final PapParameterGroup papParameters = new PapParameterGroup(CommonTestData.PAP_GROUP_NAME); + final GroupValidationResult validationResult = papParameters.validate(); + assertTrue(validationResult.isValid()); + assertEquals(CommonTestData.PAP_GROUP_NAME, papParameters.getName()); + } + + @Test + public void testPapParameterGroup_NullName() { + final PapParameterGroup papParameters = new PapParameterGroup(null); + final GroupValidationResult validationResult = papParameters.validate(); + assertFalse(validationResult.isValid()); + assertEquals(null, papParameters.getName()); + assertTrue(validationResult.getResult().contains( + "field \"name\" type \"java.lang.String\" value \"null\" INVALID, " + "must be a non-blank string")); + } + + @Test + public void testPapParameterGroup_EmptyName() { + final PapParameterGroup papParameters = new PapParameterGroup(""); + final GroupValidationResult validationResult = papParameters.validate(); + assertFalse(validationResult.isValid()); + assertEquals("", papParameters.getName()); + assertTrue(validationResult.getResult().contains( + "field \"name\" type \"java.lang.String\" value \"\" INVALID, " + "must be a non-blank string")); + } + + @Test + public void testPapParameterGroup_SetName() { + final PapParameterGroup papParameters = new PapParameterGroup(CommonTestData.PAP_GROUP_NAME); + papParameters.setName("PapNewGroup"); + final GroupValidationResult validationResult = papParameters.validate(); + assertTrue(validationResult.isValid()); + assertEquals("PapNewGroup", papParameters.getName()); + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java new file mode 100644 index 00000000..cb14748d --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPapParameterHandler.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.parameters; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.startstop.PapCommandLineArguments; + +/** + * Class to perform unit test of {@link PapParameterHandler}. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class TestPapParameterHandler { + + @Test + public void testParameterHandlerNoParameterFile() throws PolicyPapException { + final String[] noArgumentString = { "-c", "parameters/NoParameterFile.json" }; + + final PapCommandLineArguments noArguments = new PapCommandLineArguments(); + noArguments.parse(noArgumentString); + + try { + new PapParameterHandler().getParameters(noArguments); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertTrue(e.getMessage().contains("FileNotFoundException")); + } + } + + @Test + public void testParameterHandlerEmptyParameters() throws PolicyPapException { + final String[] emptyArgumentString = { "-c", "parameters/EmptyParameters.json" }; + + final PapCommandLineArguments emptyArguments = new PapCommandLineArguments(); + emptyArguments.parse(emptyArgumentString); + + try { + new PapParameterHandler().getParameters(emptyArguments); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertEquals("no parameters found in \"parameters/EmptyParameters.json\"", e.getMessage()); + } + } + + @Test + public void testParameterHandlerInvalidParameters() throws PolicyPapException { + final String[] invalidArgumentString = { "-c", "parameters/InvalidParameters.json" }; + + final PapCommandLineArguments invalidArguments = new PapCommandLineArguments(); + invalidArguments.parse(invalidArgumentString); + + try { + new PapParameterHandler().getParameters(invalidArguments); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertEquals("error reading parameters from \"parameters/InvalidParameters.json\"\n" + + "(JsonSyntaxException):java.lang.IllegalStateException: " + + "Expected a string but was BEGIN_ARRAY at line 2 column 15 path $.name", e.getMessage()); + } + } + + @Test + public void testParameterHandlerNoParameters() throws PolicyPapException { + final String[] noArgumentString = { "-c", "parameters/NoParameters.json" }; + + final PapCommandLineArguments noArguments = new PapCommandLineArguments(); + noArguments.parse(noArgumentString); + + try { + new PapParameterHandler().getParameters(noArguments); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertTrue(e.getMessage().contains( + "field \"name\" type \"java.lang.String\" value \"null\" INVALID, must be a non-blank string")); + } + } + + @Test + public void testParameterHandlerMinumumParameters() throws PolicyPapException { + final String[] minArgumentString = { "-c", "parameters/MinimumParameters.json" }; + + final PapCommandLineArguments minArguments = new PapCommandLineArguments(); + minArguments.parse(minArgumentString); + + final PapParameterGroup parGroup = new PapParameterHandler().getParameters(minArguments); + assertEquals(CommonTestData.PAP_GROUP_NAME, parGroup.getName()); + } + + @Test + public void testPapParameterGroup() throws PolicyPapException { + final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters.json" }; + + final PapCommandLineArguments arguments = new PapCommandLineArguments(); + arguments.parse(papConfigParameters); + + final PapParameterGroup parGroup = new PapParameterHandler().getParameters(arguments); + assertTrue(arguments.checkSetConfigurationFilePath()); + assertEquals(CommonTestData.PAP_GROUP_NAME, parGroup.getName()); + } + + @Test + public void testPapParameterGroup_InvalidName() throws PolicyPapException { + final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters_InvalidName.json" }; + + final PapCommandLineArguments arguments = new PapCommandLineArguments(); + arguments.parse(papConfigParameters); + + try { + new PapParameterHandler().getParameters(arguments); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertTrue(e.getMessage().contains( + "field \"name\" type \"java.lang.String\" value \" \" INVALID, must be a non-blank string")); + } + } + + @Test + public void testPapVersion() throws PolicyPapException { + final String[] papConfigParameters = { "-v" }; + final PapCommandLineArguments arguments = new PapCommandLineArguments(); + final String version = arguments.parse(papConfigParameters); + assertTrue(version.startsWith("ONAP Policy Framework PAP Service")); + } + + @Test + public void testPapHelp() throws PolicyPapException { + final String[] papConfigParameters = { "-h" }; + final PapCommandLineArguments arguments = new PapCommandLineArguments(); + final String help = arguments.parse(papConfigParameters); + assertTrue(help.startsWith("usage:")); + } + + @Test + public void testPapInvalidOption() throws PolicyPapException { + final String[] papConfigParameters = { "-d" }; + final PapCommandLineArguments arguments = new PapCommandLineArguments(); + try { + arguments.parse(papConfigParameters); + } catch (final Exception exp) { + assertTrue(exp.getMessage().startsWith("invalid command line arguments specified")); + } + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java new file mode 100644 index 00000000..8bc544b0 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/startstop/TestMain.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.startstop; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.parameters.CommonTestData; + +/** + * Class to perform unit test of {@link Main}}. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class TestMain { + + @Test + public void testMain() throws PolicyPapException { + final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters.json" }; + final Main main = new Main(papConfigParameters); + assertTrue(main.getParameters().isValid()); + assertEquals(CommonTestData.PAP_GROUP_NAME, main.getParameters().getName()); + main.shutdown(); + } + + @Test + public void testMain_NoArguments() { + final String[] papConfigParameters = {}; + final Main main = new Main(papConfigParameters); + assertTrue(main.getParameters() == null); + } + + @Test + public void testMain_InvalidArguments() { + final String[] papConfigParameters = { "parameters/PapConfigParameters.json" }; + final Main main = new Main(papConfigParameters); + assertTrue(main.getParameters() == null); + } + + @Test + public void testMain_Help() { + final String[] papConfigParameters = { "-h" }; + Main.main(papConfigParameters); + } + + @Test + public void testMain_InvalidParameters() { + final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters_InvalidName.json" }; + final Main main = new Main(papConfigParameters); + assertTrue(main.getParameters() == null); + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java new file mode 100644 index 00000000..03c3413a --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.startstop; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.parameters.CommonTestData; +import org.onap.policy.pap.main.parameters.PapParameterGroup; +import org.onap.policy.pap.main.parameters.PapParameterHandler; + + +/** + * Class to perform unit test of {@link PapActivator}}. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +public class TestPapActivator { + + @Test + public void testPapActivator() throws PolicyPapException { + final String[] papConfigParameters = { "-c", "parameters/PapConfigParameters.json" }; + + final PapCommandLineArguments arguments = new PapCommandLineArguments(papConfigParameters); + + final PapParameterGroup parGroup = new PapParameterHandler().getParameters(arguments); + + final PapActivator activator = new PapActivator(parGroup); + activator.initialize(); + assertTrue(activator.getParameterGroup().isValid()); + assertEquals(CommonTestData.PAP_GROUP_NAME, activator.getParameterGroup().getName()); + activator.terminate(); + } +} diff --git a/main/src/test/resources/parameters/EmptyParameters.json b/main/src/test/resources/parameters/EmptyParameters.json new file mode 100644 index 00000000..e69de29b diff --git a/main/src/test/resources/parameters/InvalidParameters.json b/main/src/test/resources/parameters/InvalidParameters.json new file mode 100644 index 00000000..de2040cc --- /dev/null +++ b/main/src/test/resources/parameters/InvalidParameters.json @@ -0,0 +1,3 @@ +{ + "name" : [] +} \ No newline at end of file diff --git a/main/src/test/resources/parameters/MinimumParameters.json b/main/src/test/resources/parameters/MinimumParameters.json new file mode 100644 index 00000000..ec79d586 --- /dev/null +++ b/main/src/test/resources/parameters/MinimumParameters.json @@ -0,0 +1,3 @@ +{ + "name":"PapGroup" +} diff --git a/main/src/test/resources/parameters/NoParameters.json b/main/src/test/resources/parameters/NoParameters.json new file mode 100644 index 00000000..7a73a41b --- /dev/null +++ b/main/src/test/resources/parameters/NoParameters.json @@ -0,0 +1,2 @@ +{ +} \ No newline at end of file diff --git a/main/src/test/resources/parameters/PapConfigParameters.json b/main/src/test/resources/parameters/PapConfigParameters.json new file mode 100644 index 00000000..88d00517 --- /dev/null +++ b/main/src/test/resources/parameters/PapConfigParameters.json @@ -0,0 +1,3 @@ +{ + "name":"PapGroup" +} diff --git a/main/src/test/resources/parameters/PapConfigParameters_InvalidName.json b/main/src/test/resources/parameters/PapConfigParameters_InvalidName.json new file mode 100644 index 00000000..1a466d01 --- /dev/null +++ b/main/src/test/resources/parameters/PapConfigParameters_InvalidName.json @@ -0,0 +1,3 @@ +{ + "name":" " +} -- cgit 1.2.3-korg