From ceb3ced528288d9869d14930ca88907547a20c93 Mon Sep 17 00:00:00 2001 From: "a.sreekumar" Date: Tue, 14 May 2019 15:10:11 +0000 Subject: Adding pdp simulator for testing purposes Change-Id: I809e229bf363f3b18942b20521b05e2dc06643b4 Issue-ID: POLICY-1768 Signed-off-by: a.sreekumar --- models-sim/policy-models-sim-pdp/pom.xml | 100 +++++++ .../models/sim/pdp/PdpSimulatorActivator.java | 212 +++++++++++++++ .../sim/pdp/PdpSimulatorCommandLineArguments.java | 300 +++++++++++++++++++++ .../models/sim/pdp/PdpSimulatorConstants.java | 37 +++ .../policy/models/sim/pdp/PdpSimulatorMain.java | 167 ++++++++++++ .../sim/pdp/comm/PdpStateChangeListener.java | 52 ++++ .../models/sim/pdp/comm/PdpStatusPublisher.java | 93 +++++++ .../models/sim/pdp/comm/PdpUpdateListener.java | 54 ++++ .../sim/pdp/exception/PdpSimulatorException.java | 59 ++++ .../exception/PdpSimulatorRunTimeException.java | 58 ++++ .../models/sim/pdp/handler/PdpMessageHandler.java | 151 +++++++++++ .../pdp/handler/PdpStateChangeMessageHandler.java | 125 +++++++++ .../sim/pdp/handler/PdpUpdateMessageHandler.java | 121 +++++++++ .../pdp/parameters/PdpSimulatorParameterGroup.java | 48 ++++ .../parameters/PdpSimulatorParameterHandler.java | 89 ++++++ .../sim/pdp/parameters/PdpStatusParameters.java | 52 ++++ .../ToscaPolicyTypeIdentifierParameters.java | 43 +++ .../src/main/package/docker/Dockerfile | 73 +++++ .../src/main/package/docker/docker_build.sh | 65 +++++ .../src/main/package/docker/pdp-sim.sh | 62 +++++ .../src/main/package/tarball/assembly.xml | 68 +++++ .../src/main/resources/config/OnapPfConfig.json | 9 + .../src/main/resources/config/topic.properties | 22 ++ .../src/main/resources/logback.xml | 46 ++++ .../src/main/resources/ssl/policy-keystore | Bin 0 -> 4311 bytes .../src/main/resources/ssl/policy-truststore | Bin 0 -> 124180 bytes .../src/main/resources/version.txt | 4 + .../models/sim/pdp/TestPdpSimulatorActivator.java | 117 ++++++++ .../models/sim/pdp/TestPdpSimulatorConstants.java | 37 +++ .../models/sim/pdp/TestPdpSimulatorMain.java | 106 ++++++++ .../sim/pdp/comm/TestPdpStateChangeListener.java | 180 +++++++++++++ .../models/sim/pdp/comm/TestPdpUpdateListener.java | 148 ++++++++++ .../models/sim/pdp/exception/TestExceptions.java | 38 +++ .../models/sim/pdp/parameters/CommonTestData.java | 144 ++++++++++ .../parameters/TestPdpSimulatorParameterGroup.java | 107 ++++++++ .../TestPdpSimulatorParameterHandler.java | 157 +++++++++++ .../pdp/parameters/TestPdpStatusParameters.java | 58 ++++ .../src/test/resources/EmptyConfigParameters.json | 2 + .../src/test/resources/InvalidParameters.json | 3 + .../src/test/resources/NoParameters.json | 0 .../resources/PdpSimulatorConfigParameters.json | 9 + .../PdpSimulatorConfigParameters_InvalidName.json | 4 + .../PdpSimulatorConfigParameters_sim.json | 9 + .../src/test/resources/TestConfigParameters.json | 9 + .../src/test/resources/dummyProperties.json | 43 +++ .../src/test/resources/topic.properties | 22 ++ .../src/test/resources/topic_sim.properties | 22 ++ models-sim/pom.xml | 1 + 48 files changed, 3326 insertions(+) create mode 100644 models-sim/policy-models-sim-pdp/pom.xml create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorActivator.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorCommandLineArguments.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorConstants.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorMain.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStateChangeListener.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStatusPublisher.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpUpdateListener.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorException.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorRunTimeException.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpMessageHandler.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpStateChangeMessageHandler.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpUpdateMessageHandler.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterGroup.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterHandler.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpStatusParameters.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/ToscaPolicyTypeIdentifierParameters.java create mode 100644 models-sim/policy-models-sim-pdp/src/main/package/docker/Dockerfile create mode 100644 models-sim/policy-models-sim-pdp/src/main/package/docker/docker_build.sh create mode 100644 models-sim/policy-models-sim-pdp/src/main/package/docker/pdp-sim.sh create mode 100644 models-sim/policy-models-sim-pdp/src/main/package/tarball/assembly.xml create mode 100644 models-sim/policy-models-sim-pdp/src/main/resources/config/OnapPfConfig.json create mode 100644 models-sim/policy-models-sim-pdp/src/main/resources/config/topic.properties create mode 100644 models-sim/policy-models-sim-pdp/src/main/resources/logback.xml create mode 100644 models-sim/policy-models-sim-pdp/src/main/resources/ssl/policy-keystore create mode 100644 models-sim/policy-models-sim-pdp/src/main/resources/ssl/policy-truststore create mode 100644 models-sim/policy-models-sim-pdp/src/main/resources/version.txt create mode 100644 models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/TestPdpSimulatorActivator.java create mode 100644 models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/TestPdpSimulatorConstants.java create mode 100644 models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/TestPdpSimulatorMain.java create mode 100644 models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/comm/TestPdpStateChangeListener.java create mode 100644 models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/comm/TestPdpUpdateListener.java create mode 100644 models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/exception/TestExceptions.java create mode 100644 models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/CommonTestData.java create mode 100644 models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/TestPdpSimulatorParameterGroup.java create mode 100644 models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/TestPdpSimulatorParameterHandler.java create mode 100644 models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/TestPdpStatusParameters.java create mode 100644 models-sim/policy-models-sim-pdp/src/test/resources/EmptyConfigParameters.json create mode 100644 models-sim/policy-models-sim-pdp/src/test/resources/InvalidParameters.json create mode 100644 models-sim/policy-models-sim-pdp/src/test/resources/NoParameters.json create mode 100644 models-sim/policy-models-sim-pdp/src/test/resources/PdpSimulatorConfigParameters.json create mode 100644 models-sim/policy-models-sim-pdp/src/test/resources/PdpSimulatorConfigParameters_InvalidName.json create mode 100644 models-sim/policy-models-sim-pdp/src/test/resources/PdpSimulatorConfigParameters_sim.json create mode 100644 models-sim/policy-models-sim-pdp/src/test/resources/TestConfigParameters.json create mode 100644 models-sim/policy-models-sim-pdp/src/test/resources/dummyProperties.json create mode 100644 models-sim/policy-models-sim-pdp/src/test/resources/topic.properties create mode 100644 models-sim/policy-models-sim-pdp/src/test/resources/topic_sim.properties diff --git a/models-sim/policy-models-sim-pdp/pom.xml b/models-sim/policy-models-sim-pdp/pom.xml new file mode 100644 index 000000000..e6d99ca29 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/pom.xml @@ -0,0 +1,100 @@ + + + 4.0.0 + + org.onap.policy.models.sim + policy-models-sim + 2.0.0-SNAPSHOT + + policy-models-sim-pdp + policy-models-sim-pdp + +A module that implements a simulator for PDP. + + + org.onap.policy.models + policy-models-pdp + ${project.version} + + + commons-cli + commons-cli + + + org.onap.policy.common + policy-endpoints + ${policy.common.version} + + + org.onap.policy.common + utils-test + ${policy.common.version} + + + + org.onap.policy.common + common-parameters + ${policy.common.version} + + + + + org.assertj + assertj-core + test + + + org.powermock + powermock-api-mockito + test + + + junit + junit + test + + + + + + + src/main/resources + true + + **/version.txt + + + + src/main/resources + false + + **/version.txt + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + generate-complete-tar + package + + single + + + + src/main/package/tarball/assembly.xml + + ${project.artifactId}-${project.version} + + + + + + + + diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorActivator.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorActivator.java new file mode 100644 index 000000000..be396de05 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorActivator.java @@ -0,0 +1,212 @@ +/*- + * ============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.models.sim.pdp; + +import java.util.List; +import java.util.Properties; + +import lombok.Getter; +import lombok.Setter; + + +import org.onap.policy.common.endpoints.event.comm.TopicEndpoint; +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.TopicSource; +import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.common.utils.services.ServiceManager; +import org.onap.policy.common.utils.services.ServiceManagerException; +import org.onap.policy.models.pdp.enums.PdpMessageType; +import org.onap.policy.models.sim.pdp.comm.PdpStateChangeListener; +import org.onap.policy.models.sim.pdp.comm.PdpStatusPublisher; +import org.onap.policy.models.sim.pdp.comm.PdpUpdateListener; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorRunTimeException; +import org.onap.policy.models.sim.pdp.handler.PdpMessageHandler; +import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterGroup; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class activates the PdpSimulator as a complete service together with all its handlers. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpSimulatorActivator { + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpSimulatorActivator.class); + private final PdpSimulatorParameterGroup pdpSimulatorParameterGroup; + private List topicSinks;// topics to which pdp sends pdp status + private List topicSources; // topics to which pdp listens to for messages from pap. + private static final String[] MSG_TYPE_NAMES = { "messageName" }; + + /** + * Listens for messages on the topic, decodes them into a message, and then dispatches them. + */ + private final MessageTypeDispatcher msgDispatcher; + + /** + * Used to manage the services. + */ + private ServiceManager manager; + + + @Getter + @Setter(lombok.AccessLevel.PRIVATE) + private volatile boolean alive = false; + + /** + * Instantiate the activator for onappf PDP-A. + * + * @param pdpSimulatorParameterGroup the parameters for the onappf PDP-A service + * @param topicProperties properties used to configure the topics + */ + public PdpSimulatorActivator(final PdpSimulatorParameterGroup pdpSimulatorParameterGroup, + final Properties topicProperties) { + + topicSinks = TopicEndpoint.manager.addTopicSinks(topicProperties); + topicSources = TopicEndpoint.manager.addTopicSources(topicProperties); + + final int random = (int) (Math.random() * 1000); + final String instanceId = "pdp_" + random; + LOGGER.debug("PdpSimulatorActivator initializing with instance id:" + instanceId); + try { + this.pdpSimulatorParameterGroup = pdpSimulatorParameterGroup; + this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES); + } catch (final RuntimeException e) { + throw new PdpSimulatorRunTimeException(e); + } + + final PdpUpdateListener pdpUpdateListener = new PdpUpdateListener(); + final PdpStateChangeListener pdpStateChangeListener = new PdpStateChangeListener(); + // @formatter:off + this.manager = new ServiceManager() + .addAction("topics", + () -> TopicEndpoint.manager.start(), + () -> TopicEndpoint.manager.shutdown()) + .addAction("set alive", + () -> setAlive(true), + () -> setAlive(false)) + .addAction("register pdp status context object", + () -> Registry.register(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT, + new PdpMessageHandler().createPdpStatusFromParameters(instanceId, + pdpSimulatorParameterGroup.getPdpStatusParameters())), + () -> Registry.unregister(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT)) + .addAction("topic sinks", + () -> Registry.register(PdpSimulatorConstants.REG_PDP_TOPIC_SINKS, topicSinks), + () -> Registry.unregister(PdpSimulatorConstants.REG_PDP_TOPIC_SINKS)) + .addAction("Pdp Status publisher", + () -> Registry.register(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, + new PdpStatusPublisher(topicSinks, + pdpSimulatorParameterGroup.getPdpStatusParameters().getTimeIntervalMs())), + () -> stopAndRemovePdpStatusPublisher()) + .addAction("Register pdp update listener", + () -> msgDispatcher.register(PdpMessageType.PDP_UPDATE.name(), pdpUpdateListener), + () -> msgDispatcher.unregister(PdpMessageType.PDP_UPDATE.name())) + .addAction("Register pdp state change request dispatcher", + () -> msgDispatcher.register(PdpMessageType.PDP_STATE_CHANGE.name(), pdpStateChangeListener), + () -> msgDispatcher.unregister(PdpMessageType.PDP_STATE_CHANGE.name())) + .addAction("Message Dispatcher", + () -> registerMsgDispatcher(), + () -> unregisterMsgDispatcher()); + + // @formatter:on + } + + /** + * Method to stop and unregister the pdp status publisher. + */ + private void stopAndRemovePdpStatusPublisher() { + final PdpStatusPublisher pdpStatusPublisher = + Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class); + pdpStatusPublisher.terminate(); + Registry.unregister(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER); + } + + /** + * Initialize PdpSimulator service. + * + * @throws PdpSimulatorException on errors in initializing the service + */ + public void initialize() throws PdpSimulatorException { + if (isAlive()) { + throw new IllegalStateException("activator already initialized"); + } + + try { + LOGGER.debug("PdpSimulator starting as a service . . ."); + manager.start(); + LOGGER.debug("PdpSimulator started as a service"); + } catch (final ServiceManagerException exp) { + LOGGER.error("PdpSimulator service startup failed"); + throw new PdpSimulatorException(exp.getMessage(), exp); + } + } + + /** + * Terminate PdpSimulator. + * + * @throws PdpSimulatorException on errors in terminating the service + */ + public void terminate() throws PdpSimulatorException { + if (!isAlive()) { + throw new IllegalStateException("activator is not running"); + } + try { + final PdpStatusPublisher pdpStatusPublisher = + Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class); + // send a final heartbeat with terminated status + pdpStatusPublisher.send(new PdpMessageHandler().getTerminatedPdpStatus()); + manager.stop(); + Registry.unregister(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR); + } catch (final ServiceManagerException exp) { + LOGGER.error("PdpSimulator termination failed"); + throw new PdpSimulatorException(exp.getMessage(), exp); + } + } + + /** + * Get the parameters used by the activator. + * + * @return pdpSimulatorParameterGroup the parameters of the activator + */ + public PdpSimulatorParameterGroup getParameterGroup() { + return pdpSimulatorParameterGroup; + } + + /** + * Registers the dispatcher with the topic source(s). + */ + private void registerMsgDispatcher() { + for (final TopicSource source : topicSources) { + source.register(msgDispatcher); + } + } + + /** + * Unregisters the dispatcher from the topic source(s). + */ + private void unregisterMsgDispatcher() { + for (final TopicSource source : topicSources) { + source.unregister(msgDispatcher); + } + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorCommandLineArguments.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorCommandLineArguments.java new file mode 100644 index 000000000..fb517e221 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorCommandLineArguments.java @@ -0,0 +1,300 @@ +/*- + * ============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.models.sim.pdp; + +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.apache.log4j.chainsaw.Main; + +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorRunTimeException; + +/** + * This class reads and handles command line parameters for the pdp simulator. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpSimulatorCommandLineArguments { + + private static final String FILE_MESSAGE_PREAMBLE = " file \""; + private static final int HELP_LINE_LENGTH = 120; + + private final Options options; + private String configurationFilePath = null; + private String propertyFilePath = null; + + /** + * Construct the options for the CLI editor. + */ + public PdpSimulatorCommandLineArguments() { + //@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 pdp simulator") + .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 pdp simulator parameters") + .hasArg() + .argName("CONFIG_FILE") + .required(false) + .type(String.class) + .build()); + options.addOption(Option.builder("p") + .longOpt("property-file") + .desc("the full path to the topic property file to use, " + + "the property file contains the pdp simulator topic properties") + .hasArg() + .argName("PROP_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 PdpSimulatorCommandLineArguments(final String[] args) { + // Set up the options with the default constructor + this(); + + // Parse the arguments + try { + parse(args); + } catch (final PdpSimulatorException e) { + throw new PdpSimulatorRunTimeException("parse error on pdp simulator 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 PdpSimulatorException on command argument errors + */ + public String parse(final String[] args) throws PdpSimulatorException { + // Clear all our arguments + setConfigurationFilePath(null); + setPropertyFilePath(null); + + CommandLine commandLine = null; + try { + commandLine = new DefaultParser().parse(options, args); + } catch (final ParseException e) { + throw new PdpSimulatorException("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 PdpSimulatorException("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')); + } + + if (commandLine.hasOption('p')) { + setPropertyFilePath(commandLine.getOptionValue('p')); + } + + return null; + } + + /** + * Validate the command line options. + * + * @throws PdpSimulatorException on command argument validation errors + */ + public void validate() throws PdpSimulatorException { + validateReadableFile("pdp simulator configuration", configurationFilePath); + validateReadableFile("pdp simulator properties", propertyFilePath); + } + + /** + * Print version information for pdp simulator. + * + * @return the version string + */ + public String version() { + return ResourceUtils.getResourceAsString("src/main/resources/version.txt"); + } + + /** + * Print help information for pdp simulator. + * + * @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; + } + + /** + * Gets the property file path. + * + * @return the property file path + */ + public String getPropertyFilePath() { + return propertyFilePath; + } + + /** + * Gets the full expanded property file path. + * + * @return the property file path + */ + public String getFullPropertyFilePath() { + return ResourceUtils.getFilePath4Resource(getPropertyFilePath()); + } + + /** + * Sets the property file path. + * + * @param propertyFilePath the property file path + */ + public void setPropertyFilePath(final String propertyFilePath) { + this.propertyFilePath = propertyFilePath; + + } + + /** + * Check set property file path. + * + * @return true, if check set property file path + */ + public boolean checkSetPropertyFilePath() { + return propertyFilePath != null && propertyFilePath.length() > 0; + } + + /** + * Validate readable file. + * + * @param fileTag the file tag + * @param fileName the file name + * @throws PdpSimulatorException on the file name passed as a parameter + */ + private void validateReadableFile(final String fileTag, final String fileName) throws PdpSimulatorException { + if (fileName == null || fileName.length() == 0) { + throw new PdpSimulatorException(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 PdpSimulatorException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); + } + + final File theFile = new File(fileUrl.getPath()); + if (!theFile.exists()) { + throw new PdpSimulatorException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); + } + if (!theFile.isFile()) { + throw new PdpSimulatorException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file"); + } + if (!theFile.canRead()) { + throw new PdpSimulatorException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is ureadable"); + } + } + +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorConstants.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorConstants.java new file mode 100644 index 000000000..22dbc4610 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorConstants.java @@ -0,0 +1,37 @@ +/*- + * ============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.models.sim.pdp; + +/** + * Names of various items contained in the Registry. + */ +public class PdpSimulatorConstants { + // Registry keys + public static final String REG_PDP_SIMULATOR_ACTIVATOR = "object:activator/pdp_simulator"; + public static final String REG_PDP_STATUS_OBJECT = "object:pdp/status"; + public static final String REG_PDP_TOSCA_POLICY_LIST = "object:pdp/tosca/policy/list"; + public static final String REG_PDP_STATUS_PUBLISHER = "object:pdp/status/publisher"; + public static final String REG_PDP_TOPIC_SINKS = "object:pdp/topic/sinks"; + + private PdpSimulatorConstants() { + super(); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorMain.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorMain.java new file mode 100644 index 000000000..f5892d5c8 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/PdpSimulatorMain.java @@ -0,0 +1,167 @@ +/*- + * ============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.models.sim.pdp; + +import java.io.FileInputStream; +import java.util.Arrays; +import java.util.Properties; + + +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; +import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterGroup; +import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class initiates PdpSimulator. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpSimulatorMain { + + private static final String PDP_SIMULATOR_FAIL_MSG = "start of pdp simulator failed"; + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpSimulatorMain.class); + + private PdpSimulatorActivator activator; + private PdpSimulatorParameterGroup parameterGroup; + + /** + * Instantiates the PdpSimulator. + * + * @param args the command line arguments + */ + public PdpSimulatorMain(final String[] args) { + LOGGER.info("In PdpSimulator with parameters ", Arrays.toString(args)); + + // Check the arguments + final PdpSimulatorCommandLineArguments arguments = new PdpSimulatorCommandLineArguments(); + 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.debug(argumentMessage); + return; + } + // Validate that the arguments are sane + arguments.validate(); + } catch (final PdpSimulatorException e) { + LOGGER.error(PDP_SIMULATOR_FAIL_MSG, e); + return; + } + + // Read the parameters + try { + parameterGroup = new PdpSimulatorParameterHandler().getParameters(arguments); + } catch (final Exception e) { + LOGGER.error(PDP_SIMULATOR_FAIL_MSG, e); + return; + } + + // Read the properties + final Properties topicProperties = new Properties(); + try { + final String propFile = arguments.getFullPropertyFilePath(); + try (FileInputStream stream = new FileInputStream(propFile)) { + topicProperties.load(stream); + } + } catch (final Exception e) { + LOGGER.error(PDP_SIMULATOR_FAIL_MSG, e); + return; + } + + // create the activator + activator = new PdpSimulatorActivator(parameterGroup, topicProperties); + Registry.register(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR, activator); + // Start the activator + try { + activator.initialize(); + } catch (final PdpSimulatorException e) { + LOGGER.error("start of PdpSimulator failed, used parameters are {}", Arrays.toString(args), e); + Registry.unregister(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR); + return; + } + + // Add a shutdown hook to shut everything down in an orderly manner + Runtime.getRuntime().addShutdownHook(new PdpSimulatorShutdownHookClass()); + + LOGGER.info("Started PdpSimulator service"); + } + + /** + * Get the parameters specified in JSON. + * + * @return parameterGroup the parameters + */ + public PdpSimulatorParameterGroup getParameters() { + return parameterGroup; + } + + + /** + * Shut down Execution. + * + * @throws PdpSimulatorException on shutdown errors + */ + public void shutdown() throws PdpSimulatorException { + // clear the parameterGroup variable + parameterGroup = null; + + // clear the pdp simulator activator + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } + + /** + * The Class PdpSimulatorShutdownHookClass terminates the pdp simulator when its run method is called. + */ + private class PdpSimulatorShutdownHookClass extends Thread { + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + try { + // Shutdown the pdp simulator service and wait for everything to stop + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } catch (final PdpSimulatorException e) { + LOGGER.warn("error occured during shut down of the pdp simulator service", e); + } + } + } + + /** + * The main method. + * + * @param args the arguments + * + */ + public static void main(final String[] args) { + new PdpSimulatorMain(args); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStateChangeListener.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStateChangeListener.java new file mode 100644 index 000000000..ebe493a69 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStateChangeListener.java @@ -0,0 +1,52 @@ +/*- + * ============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.models.sim.pdp.comm; + +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.listeners.ScoListener; +import org.onap.policy.common.utils.coder.StandardCoderObject; +import org.onap.policy.models.pdp.concepts.PdpStateChange; +import org.onap.policy.models.sim.pdp.handler.PdpStateChangeMessageHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Listener for Pdp state change messages sent by PAP. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpStateChangeListener extends ScoListener { + private static final Logger LOGGER = LoggerFactory.getLogger(PdpStateChangeListener.class); + + /** + * Constructs the object. + */ + public PdpStateChangeListener() { + super(PdpStateChange.class); + } + + @Override + public void onTopicEvent(final CommInfrastructure infra, final String topic, final StandardCoderObject sco, + final PdpStateChange pdpStateChangeMsg) { + LOGGER.debug("Pdp state change message received from PAP. - {}", pdpStateChangeMsg); + new PdpStateChangeMessageHandler().handlePdpStateChangeEvent(pdpStateChangeMsg); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStatusPublisher.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStatusPublisher.java new file mode 100644 index 000000000..33c9df778 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpStatusPublisher.java @@ -0,0 +1,93 @@ +/*- + * ============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.models.sim.pdp.comm; + +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; + +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient; +import org.onap.policy.models.pdp.concepts.PdpStatus; +import org.onap.policy.models.sim.pdp.handler.PdpMessageHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class is used to send pdp status messages to pap using TopicSinkClient. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpStatusPublisher extends TimerTask { + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpStatusPublisher.class); + + private TopicSinkClient topicSinkClient; + private Timer timer; + private long interval; + + /** + * Constructor for instantiating PdpStatusPublisher. + * + * @param topicSinks the topic sinks + * @param interval time interval to send pdp status + */ + public PdpStatusPublisher(final List topicSinks, final long interval) { + this.topicSinkClient = new TopicSinkClient(topicSinks.get(0)); + this.interval = interval; + timer = new Timer(false); + timer.scheduleAtFixedRate(this, 0, interval); + } + + @Override + public void run() { + final PdpStatus pdpStatus = new PdpMessageHandler().createPdpStatusFromContext(); + topicSinkClient.send(pdpStatus); + LOGGER.debug("Sent heartbeat to PAP - {}", pdpStatus); + } + + /** + * Terminates the current timer. + */ + public void terminate() { + timer.cancel(); + timer.purge(); + } + + /** + * Get the current time interval used by the timer task. + * + * @return interval the current time interval + */ + public long getInterval() { + return interval; + } + + /** + * Method to send pdp status message to pap on demand. + * + * @param pdpStatus the pdp status + */ + public void send(final PdpStatus pdpStatus) { + topicSinkClient.send(pdpStatus); + LOGGER.debug("Sent pdp status message to PAP - {}", pdpStatus); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpUpdateListener.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpUpdateListener.java new file mode 100644 index 000000000..52b1b11f0 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/comm/PdpUpdateListener.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.models.sim.pdp.comm; + +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.listeners.ScoListener; +import org.onap.policy.common.utils.coder.StandardCoderObject; +import org.onap.policy.models.pdp.concepts.PdpUpdate; +import org.onap.policy.models.sim.pdp.handler.PdpUpdateMessageHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Listener for Pdp update messages sent by PAP. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpUpdateListener extends ScoListener { + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpUpdateListener.class); + + /** + * Constructs the object. + */ + public PdpUpdateListener() { + super(PdpUpdate.class); + } + + @Override + public void onTopicEvent(final CommInfrastructure infra, final String topic, final StandardCoderObject sco, + final PdpUpdate pdpUpdateMsg) { + LOGGER.debug("Pdp update message received from PAP - {}", pdpUpdateMsg); + new PdpUpdateMessageHandler().handlePdpUpdateEvent(pdpUpdateMsg); + + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorException.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorException.java new file mode 100644 index 000000000..9d460ad77 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorException.java @@ -0,0 +1,59 @@ +/*- + * ============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.models.sim.pdp.exception; + +/** + * This exception will be called if an error occurs in pdp simulator. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpSimulatorException extends Exception { + private static final long serialVersionUID = -510646141043975917L; + + /** + * Instantiates a new pdp simulator exception with a message. + * + * @param message the message + */ + public PdpSimulatorException(final String message) { + super(message); + } + + /** + * Instantiates a new pdp simulator exception caused by an exception. + * + * @param exception the exception that caused this exception to be thrown + */ + public PdpSimulatorException(final Exception exception) { + super(exception); + } + + /** + * Instantiates a new pdp simulator exception with a message and a caused by an exception. + * + * @param message the message + * @param exception the exception that caused this exception to be thrown + */ + public PdpSimulatorException(final String message, final Exception exception) { + super(message, exception); + } + +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorRunTimeException.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorRunTimeException.java new file mode 100644 index 000000000..4b6839f56 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/exception/PdpSimulatorRunTimeException.java @@ -0,0 +1,58 @@ +/*- + * ============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.models.sim.pdp.exception; + +/** + * This runtime exception will be called if a runtime error occurs when using pdp simulator. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpSimulatorRunTimeException extends RuntimeException { + private static final long serialVersionUID = -6024353312002272098L; + + /** + * Instantiates a new pdp simulator runtime exception with a message. + * + * @param message the message + */ + public PdpSimulatorRunTimeException(final String message) { + super(message); + } + + /** + * Instantiates a new pdp simulator runtime exception caused by an exception. + * + * @param exception the exception that caused this exception to be thrown + */ + public PdpSimulatorRunTimeException(final Exception exception) { + super(exception); + } + + /** + * Instantiates a new pdp simulator runtime exception with a message and caused by an exception. + * + * @param message the message + * @param exception the exception that caused this exception to be thrown + */ + public PdpSimulatorRunTimeException(final String message, final Exception exception) { + super(message, exception); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpMessageHandler.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpMessageHandler.java new file mode 100644 index 000000000..d4296c6df --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpMessageHandler.java @@ -0,0 +1,151 @@ +/*- + * ============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.models.sim.pdp.handler; + +import java.util.ArrayList; +import java.util.List; + + +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.pdp.concepts.PdpResponseDetails; +import org.onap.policy.models.pdp.concepts.PdpStatus; +import org.onap.policy.models.pdp.enums.PdpHealthStatus; +import org.onap.policy.models.pdp.enums.PdpResponseStatus; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.sim.pdp.PdpSimulatorConstants; +import org.onap.policy.models.sim.pdp.parameters.PdpStatusParameters; +import org.onap.policy.models.sim.pdp.parameters.ToscaPolicyTypeIdentifierParameters; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; + +/** + * This class supports the handling of pdp messages. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpMessageHandler { + + /** + * Method to create PdpStatus message from the parameters which will be saved to the context. + * + * @param instanceId instance id of the pdp + * @param pdpStatusParameters pdp status parameters read from the configuration file + * + * @return pdpStatus the pdp status message + */ + public PdpStatus createPdpStatusFromParameters(final String instanceId, + final PdpStatusParameters pdpStatusParameters) { + final PdpStatus pdpStatus = new PdpStatus(); + pdpStatus.setPdpType(pdpStatusParameters.getPdpType()); + pdpStatus.setState(PdpState.PASSIVE); + pdpStatus.setHealthy(PdpHealthStatus.HEALTHY); + pdpStatus.setDescription(pdpStatusParameters.getDescription()); + pdpStatus.setName(instanceId); + pdpStatus.setSupportedPolicyTypes(getSupportedPolicyTypesFromParameters(pdpStatusParameters)); + return pdpStatus; + } + + /** + * Method to get supported policy types from the parameters. + * + * @param pdpStatusParameters pdp status parameters + * @return supportedPolicyTypes list of PolicyTypeIdent + */ + private List getSupportedPolicyTypesFromParameters( + final PdpStatusParameters pdpStatusParameters) { + final List supportedPolicyTypes = + new ArrayList<>(pdpStatusParameters.getSupportedPolicyTypes().size()); + for (final ToscaPolicyTypeIdentifierParameters policyTypeIdentParameters : pdpStatusParameters + .getSupportedPolicyTypes()) { + supportedPolicyTypes.add(new ToscaPolicyTypeIdentifier(policyTypeIdentParameters.getName(), + policyTypeIdentParameters.getVersion())); + } + return supportedPolicyTypes; + } + + /** + * Method to create PdpStatus message from the context, which is to be sent by pdp simulator to pap. + * + * @return PdpStatus the pdp status message + */ + public PdpStatus createPdpStatusFromContext() { + final PdpStatus pdpStatusContext = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); + final PdpStatus pdpStatus = new PdpStatus(); + pdpStatus.setName(pdpStatusContext.getName()); + pdpStatus.setPdpType(pdpStatusContext.getPdpType()); + pdpStatus.setState(pdpStatusContext.getState()); + pdpStatus.setHealthy(pdpStatusContext.getHealthy()); + pdpStatus.setDescription(pdpStatusContext.getDescription()); + pdpStatus.setSupportedPolicyTypes(pdpStatusContext.getSupportedPolicyTypes()); + pdpStatus.setPolicies(pdpStatusContext.getPolicies()); + pdpStatus.setPdpGroup(pdpStatusContext.getPdpGroup()); + pdpStatus.setPdpSubgroup(pdpStatusContext.getPdpSubgroup()); + return pdpStatus; + } + + /** + * Method to get a final pdp status when the simulator is shut down. + * + * @return PdpStatus the pdp status message + */ + public PdpStatus getTerminatedPdpStatus() { + final PdpStatus pdpStatusInContext = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); + pdpStatusInContext.setState(PdpState.TERMINATED); + pdpStatusInContext.setDescription("Pdp Simulator shutting down."); + return createPdpStatusFromContext(); + } + + /** + * Method create PdpResponseDetails which will be sent as part of pdp status to PAP. + * + * @param requestId request id of the PdpUpdate message from pap + * @param status response status to be sent back + * @param responseMessage response message to be sent back + * + * @return PdpResponseDetails + */ + public PdpResponseDetails createPdpResonseDetails(final String requestId, final PdpResponseStatus status, + final String responseMessage) { + final PdpResponseDetails pdpResponseDetails = new PdpResponseDetails(); + pdpResponseDetails.setResponseTo(requestId); + pdpResponseDetails.setResponseStatus(status); + pdpResponseDetails.setResponseMessage(responseMessage); + return pdpResponseDetails; + } + + /** + * Method to retrieve list of ToscaPolicyIdentifier from the list of ToscaPolicy. + * + * @param policies list of ToscaPolicy + * + * @return policyTypeIdentifiers + */ + public List getToscaPolicyIdentifiers(final List policies) { + final List policyIdentifiers = new ArrayList<>(policies.size()); + for (final ToscaPolicy policy : policies) { + if (null != policy.getName() && null != policy.getVersion()) { + policyIdentifiers.add(new ToscaPolicyIdentifier(policy.getName(), policy.getVersion())); + } + } + return policyIdentifiers; + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpStateChangeMessageHandler.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpStateChangeMessageHandler.java new file mode 100644 index 000000000..ec1fa25a3 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpStateChangeMessageHandler.java @@ -0,0 +1,125 @@ +/*- + * ============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.models.sim.pdp.handler; + +import java.util.List; + +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.pdp.concepts.PdpResponseDetails; +import org.onap.policy.models.pdp.concepts.PdpStateChange; +import org.onap.policy.models.pdp.concepts.PdpStatus; +import org.onap.policy.models.pdp.enums.PdpResponseStatus; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.sim.pdp.PdpSimulatorConstants; +import org.onap.policy.models.sim.pdp.comm.PdpStatusPublisher; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class supports the handling of pdp state change messages. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpStateChangeMessageHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpStateChangeMessageHandler.class); + + /** + * Method which handles a pdp state change event from PAP. + * + * @param pdpStateChangeMsg pdp state change message + */ + public void handlePdpStateChangeEvent(final PdpStateChange pdpStateChangeMsg) { + final PdpStatus pdpStatusContext = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); + final PdpStatusPublisher pdpStatusPublisher = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER); + final PdpMessageHandler pdpMessageHandler = new PdpMessageHandler(); + PdpResponseDetails pdpResponseDetails = null; + if (pdpStateChangeMsg.appliesTo(pdpStatusContext.getName(), pdpStatusContext.getPdpGroup(), + pdpStatusContext.getPdpSubgroup())) { + switch (pdpStateChangeMsg.getState()) { + case PASSIVE: + pdpResponseDetails = handlePassiveState(pdpStateChangeMsg, pdpStatusContext, pdpMessageHandler); + break; + case ACTIVE: + pdpResponseDetails = handleActiveState(pdpStateChangeMsg, pdpStatusContext, pdpMessageHandler); + break; + default: + break; + } + final PdpStatus pdpStatus = pdpMessageHandler.createPdpStatusFromContext(); + pdpStatus.setResponse(pdpResponseDetails); + pdpStatus.setDescription("Pdp status response message for PdpStateChange"); + pdpStatusPublisher.send(pdpStatus); + } + } + + /** + * Method to handle when the new state from pap is active. + * + * @param pdpStateChangeMsg pdp state change message + * @param pdpStatusContext pdp status object in memory + * @param pdpMessageHandler the pdp message handler + * @return pdpResponseDetails pdp response + */ + private PdpResponseDetails handleActiveState(final PdpStateChange pdpStateChangeMsg, + final PdpStatus pdpStatusContext, final PdpMessageHandler pdpMessageHandler) { + PdpResponseDetails pdpResponseDetails = null; + if (pdpStatusContext.getState().equals(PdpState.ACTIVE)) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp already in active state"); + } else { + final List policies = Registry.get(PdpSimulatorConstants.REG_PDP_TOSCA_POLICY_LIST); + if (policies.isEmpty()) { + pdpStatusContext.setState(PdpState.ACTIVE); + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "State changed to active. No policies found."); + } else { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp started. State changed to active."); + pdpStatusContext.setState(PdpState.ACTIVE); + } + } + return pdpResponseDetails; + } + + /** + * Method to handle when the new state from pap is passive. + * + * @param pdpStateChangeMsg pdp state change message + * @param pdpStatusContext pdp status object in memory + * @param pdpMessageHandler the pdp message handler + * @return pdpResponseDetails pdp response + */ + private PdpResponseDetails handlePassiveState(final PdpStateChange pdpStateChangeMsg, + final PdpStatus pdpStatusContext, final PdpMessageHandler pdpMessageHandler) { + PdpResponseDetails pdpResponseDetails = null; + if (pdpStatusContext.getState().equals(PdpState.PASSIVE)) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp already in passive state"); + } else { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp state changed from Active to Passive."); + pdpStatusContext.setState(PdpState.PASSIVE); + } + return pdpResponseDetails; + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpUpdateMessageHandler.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpUpdateMessageHandler.java new file mode 100644 index 000000000..94499f43d --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/handler/PdpUpdateMessageHandler.java @@ -0,0 +1,121 @@ +/*- + * ============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.models.sim.pdp.handler; + +import java.util.List; + + +import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.pdp.concepts.PdpResponseDetails; +import org.onap.policy.models.pdp.concepts.PdpStatus; +import org.onap.policy.models.pdp.concepts.PdpUpdate; +import org.onap.policy.models.pdp.enums.PdpResponseStatus; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.sim.pdp.PdpSimulatorConstants; +import org.onap.policy.models.sim.pdp.comm.PdpStatusPublisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class supports the handling of pdp update messages. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpUpdateMessageHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpUpdateMessageHandler.class); + + /** + * Method which handles a pdp update event from PAP. + * + * @param pdpUpdateMsg pdp update message + */ + public void handlePdpUpdateEvent(final PdpUpdate pdpUpdateMsg) { + final PdpMessageHandler pdpMessageHandler = new PdpMessageHandler(); + final PdpStatus pdpStatusContext = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); + PdpResponseDetails pdpResponseDetails = null; + if (pdpUpdateMsg.appliesTo(pdpStatusContext.getName(), pdpStatusContext.getPdpGroup(), + pdpStatusContext.getPdpSubgroup())) { + final PdpStatusPublisher pdpStatusPublisher = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER); + if (checkIfAlreadyHandled(pdpUpdateMsg, pdpStatusContext)) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp already updated"); + } else { + if (null != pdpUpdateMsg.getPdpHeartbeatIntervalMs() && pdpUpdateMsg.getPdpHeartbeatIntervalMs() > 0 + && pdpStatusPublisher.getInterval() != pdpUpdateMsg.getPdpHeartbeatIntervalMs()) { + updateInterval(pdpUpdateMsg.getPdpHeartbeatIntervalMs()); + } + pdpStatusContext.setPdpGroup(pdpUpdateMsg.getPdpGroup()); + pdpStatusContext.setPdpSubgroup(pdpUpdateMsg.getPdpSubgroup()); + pdpStatusContext + .setPolicies(new PdpMessageHandler().getToscaPolicyIdentifiers(pdpUpdateMsg.getPolicies())); + if (pdpStatusContext.getState().equals(PdpState.ACTIVE)) { + if (!pdpUpdateMsg.getPolicies().isEmpty()) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp engine started and policies are running."); + } + } + Registry.registerOrReplace(PdpSimulatorConstants.REG_PDP_TOSCA_POLICY_LIST, pdpUpdateMsg.getPolicies()); + if (null == pdpResponseDetails) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp update successful."); + } + } + final PdpStatusPublisher pdpStatusPublisherTemp = + Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER); + final PdpStatus pdpStatus = pdpMessageHandler.createPdpStatusFromContext(); + pdpStatus.setResponse(pdpResponseDetails); + pdpStatus.setDescription("Pdp status response message for PdpUpdate"); + pdpStatusPublisherTemp.send(pdpStatus); + } + } + + + /** + * Method checks if the Pdp update message is already handled by checking the values in the context. + * + * @param pdpUpdateMsg pdp update message received from pap + * @param pdpStatusContext values saved in context memory + * @return boolean flag which tells if the information is same or not + */ + private boolean checkIfAlreadyHandled(final PdpUpdate pdpUpdateMsg, final PdpStatus pdpStatusContext) { + return null != pdpStatusContext.getPdpGroup() + && pdpStatusContext.getPdpGroup().equals(pdpUpdateMsg.getPdpGroup()) + && null != pdpStatusContext.getPdpSubgroup() + && pdpStatusContext.getPdpSubgroup().equals(pdpUpdateMsg.getPdpSubgroup()) + && null != pdpStatusContext.getPolicies() && new PdpMessageHandler() + .getToscaPolicyIdentifiers(pdpUpdateMsg.getPolicies()).equals(pdpStatusContext.getPolicies()); + } + + /** + * Method to update the time interval used by the timer task. + * + * @param interval time interval received in the pdp update message from pap + */ + public void updateInterval(final long interval) { + final PdpStatusPublisher pdpStatusPublisher = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER); + pdpStatusPublisher.terminate(); + final List topicSinks = Registry.get(PdpSimulatorConstants.REG_PDP_TOPIC_SINKS); + Registry.registerOrReplace(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, + new PdpStatusPublisher(topicSinks, interval)); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterGroup.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterGroup.java new file mode 100644 index 000000000..58c583901 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterGroup.java @@ -0,0 +1,48 @@ +/*- + * ============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.models.sim.pdp.parameters; + +import lombok.Getter; + +import org.onap.policy.common.parameters.ParameterGroupImpl; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +/** + * Class to hold all parameters needed for pdp simulator component. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +@NotNull +@NotBlank +@Getter +public class PdpSimulatorParameterGroup extends ParameterGroupImpl { + private PdpStatusParameters pdpStatusParameters; + + /** + * Create the pdp simulator parameter group. + * + * @param name the parameter group name + */ + public PdpSimulatorParameterGroup(final String name) { + super(name); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterHandler.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterHandler.java new file mode 100644 index 000000000..2c5ccebf9 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpSimulatorParameterHandler.java @@ -0,0 +1,89 @@ +/*- + * ============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.models.sim.pdp.parameters; + +import java.io.File; + + +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.models.sim.pdp.PdpSimulatorCommandLineArguments; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class handles reading, parsing and validating of pdp simulator parameters from JSON files. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpSimulatorParameterHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(PdpSimulatorParameterHandler.class); + private static final Coder CODER = new StandardCoder(); + + /** + * Read the parameters from the parameter file. + * + * @param arguments the arguments passed to pdp simulator + * @return the parameters read from the configuration file + * @throws PdpSimulatorException on parameter exceptions + */ + public PdpSimulatorParameterGroup getParameters(final PdpSimulatorCommandLineArguments arguments) + throws PdpSimulatorException { + PdpSimulatorParameterGroup pdpSimulatorParameterGroup = null; + + // Read the parameters + try { + // Read the parameters from JSON + final File file = new File(arguments.getFullConfigurationFilePath()); + pdpSimulatorParameterGroup = CODER.decode(file, PdpSimulatorParameterGroup.class); + } catch (final CoderException e) { + final String errorMessage = "error reading parameters from \"" + arguments.getConfigurationFilePath() + + "\"\n" + "(" + e.getClass().getSimpleName() + "):" + e.getMessage(); + LOGGER.error(errorMessage, e); + throw new PdpSimulatorException(errorMessage, e); + } + + // The JSON processing returns null if there is an empty file + if (pdpSimulatorParameterGroup == null) { + final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\""; + LOGGER.error(errorMessage); + throw new PdpSimulatorException(errorMessage); + } + + // validate the parameters + final GroupValidationResult validationResult = pdpSimulatorParameterGroup.validate(); + if (!validationResult.isValid()) { + String returnMessage = + "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n"; + returnMessage += validationResult.getResult(); + + LOGGER.error(returnMessage); + throw new PdpSimulatorException(returnMessage); + } + + return pdpSimulatorParameterGroup; + } + +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpStatusParameters.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpStatusParameters.java new file mode 100644 index 000000000..e59ec52b7 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/PdpStatusParameters.java @@ -0,0 +1,52 @@ +/*- + * ============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.models.sim.pdp.parameters; + +import java.util.List; + +import lombok.Getter; + +import org.onap.policy.common.parameters.ParameterGroupImpl; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +/** + * Class to hold all parameters needed for pdpstatus. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +@NotNull +@NotBlank +@Getter +public class PdpStatusParameters extends ParameterGroupImpl { + + @Min(value = 1) + private long timeIntervalMs; + + private String pdpType; + private String description; + private List supportedPolicyTypes; + + public PdpStatusParameters() { + super(PdpStatusParameters.class.getSimpleName()); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/ToscaPolicyTypeIdentifierParameters.java b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/ToscaPolicyTypeIdentifierParameters.java new file mode 100644 index 000000000..622b41122 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/java/org/onap/policy/models/sim/pdp/parameters/ToscaPolicyTypeIdentifierParameters.java @@ -0,0 +1,43 @@ +/*- + * ============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.models.sim.pdp.parameters; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; + +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +/** + * Class to hold all parameters needed for PolicyTypeIdent. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +@NotNull +@NotBlank +@Getter +@Setter +@EqualsAndHashCode +public class ToscaPolicyTypeIdentifierParameters { + private String name; + private String version; +} diff --git a/models-sim/policy-models-sim-pdp/src/main/package/docker/Dockerfile b/models-sim/policy-models-sim-pdp/src/main/package/docker/Dockerfile new file mode 100644 index 000000000..93a3c9b63 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/package/docker/Dockerfile @@ -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========================================================= +# + +# +# Docker file to build an image that runs the PDP simulator on Java 8 in alpine +# + +FROM onap/policy-common-alpine:1.4.0 + +LABEL maintainer="Policy Team" + +ARG POLICY_LOGS=/var/log/onap/policy/pdp-sim + +ENV POLICY_HOME=/opt/app/policy +ENV POLICY_LOGS=${POLICY_LOGS} + +RUN apk add --no-cache --update \ + bash \ + nss \ + procps \ + coreutils \ + findutils \ + grep \ + zip \ + unzip \ + curl \ + wget \ + openssh \ + iproute2 \ + iputils \ + vim \ + openjdk8 + +# Create PDP simulator user and group +# Add simulator-specific directories and set ownership as the simulator user +RUN mkdir -p ${POLICY_HOME}/pdp-sim \ + && mkdir -p ${POLICY_HOME}/pdp-sim/bin \ + && mkdir -p ${POLICY_LOGS} \ + && chown -R policy:policy ${POLICY_LOGS} \ + && mkdir /packages + +# Unpack the tarball +COPY policy-models-sim-pdp-tarball.tar.gz /packages +RUN tar xvfz /packages/policy-models-sim-pdp-tarball.tar.gz --directory ${POLICY_HOME}/pdp-sim \ + && rm /packages/policy-models-sim-pdp-tarball.tar.gz + +# Ensure everything has the correct permissions +# Copy examples to PDP simulator user area +COPY pdp-sim.sh ${POLICY_HOME}/pdp-sim/bin +RUN find /opt/app -type d -perm 755 \ + && find /opt/app -type f -perm 644 \ + && chmod a+x ${POLICY_HOME}/pdp-sim/bin/* + +USER policy +ENV PATH ${POLICY_HOME}/pdp-sim/bin:$PATH +ENTRYPOINT [ "bash", "pdp-sim.sh" ] diff --git a/models-sim/policy-models-sim-pdp/src/main/package/docker/docker_build.sh b/models-sim/policy-models-sim-pdp/src/main/package/docker/docker_build.sh new file mode 100644 index 000000000..eca68cb17 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/package/docker/docker_build.sh @@ -0,0 +1,65 @@ +#!/bin/bash +# +# ============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========================================================= +# +# +# Script to build a Docker file for the PDP simulator. The docker image +# generated by this script should NOT be placed in the ONAP nexus, it is +# only for testing purposes. +# + +if [ -z "$PDP_SIM_HOME" ] +then + PDP_SIM_HOME=`pwd` +fi + +# Check for the dockerfile +if [ ! -f "$PDP_SIM_HOME/src/main/package/docker/Dockerfile" ] +then + echo docker file "$PDP_SIM_HOME/src/main/package/docker/Dockerfile" not found + exit 1 +fi + +# Check for the start script +if [ ! -f "$PDP_SIM_HOME/src/main/package/docker/pdp-sim.sh" ] +then + echo start script "$PDP_SIM_HOME/src/main/package/docker/pdp-sim.sh" not found + exit 1 +fi + +# Check for the tarball +tarball_count=`ls $PDP_SIM_HOME/target/policy-models-sim-pdp-*-SNAPSHOT-tarball.tar.gz 2> /dev/null | wc | awk '{print $1}'` +if [ "$tarball_count" -ne "1" ] +then + echo one and only one tarball should exist in the target directory + exit 2 +fi + +# Set up the docker build +rm -fr $PDP_SIM_HOME/target/docker +mkdir $PDP_SIM_HOME/target/docker +cp $PDP_SIM_HOME/src/main/package/docker/Dockerfile $PDP_SIM_HOME/target/docker +cp $PDP_SIM_HOME/src/main/package/docker/pdp-sim.sh $PDP_SIM_HOME/target/docker +cp $PDP_SIM_HOME/target/policy-models-sim-pdp-*-SNAPSHOT-tarball.tar.gz $PDP_SIM_HOME/target/docker/policy-models-sim-pdp-tarball.tar.gz + +# Run the docker build +cd $PDP_SIM_HOME/target +docker build -t pdp/simulator docker + + diff --git a/models-sim/policy-models-sim-pdp/src/main/package/docker/pdp-sim.sh b/models-sim/policy-models-sim-pdp/src/main/package/docker/pdp-sim.sh new file mode 100644 index 000000000..b0e3ba0e5 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/package/docker/pdp-sim.sh @@ -0,0 +1,62 @@ +#!/bin/bash +# +# ============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========================================================= +# + +if [ -z "$PDP_SIM_HOME" ] +then + PDP_SIM_HOME=/opt/app/policy/pdp-sim +fi + +JAVA_HOME=/usr/lib/jvm/java-1.8-openjdk +KEYSTORE="${PDP_SIM_HOME}/etc/ssl/policy-keystore" +KEYSTORE_PASSWD="Pol1cy_0nap" +TRUSTSTORE="${PDP_SIM_HOME}/etc/ssl/policy-truststore" +TRUSTSTORE_PASSWD="Pol1cy_0nap" + +if [ "$#" -eq 2 ] +then + CONFIG_FILE=$1 + PROPERTIES_FILE=$2 +else + CONFIG_FILE=${CONFIG_FILE} + PROPERTIES_FILE=${PROPERTIES_FILE} +fi + +if [ -z "$CONFIG_FILE" ] +then + CONFIG_FILE="$PDP_SIM_HOME/etc/config/OnapPfConfig.json" +fi + +if [ -z "$PROPERTIES_FILE" ] +then + PROPERTIES_FILE="$PDP_SIM_HOME/etc/config/topic.properties" +fi + +echo "PDP simulatior configuration file: $CONFIG_FILE and properties file: $PROPERTIES_FILE" + +$JAVA_HOME/bin/java \ + -cp "$PDP_SIM_HOME/etc:$PDP_SIM_HOME/lib/*" \ + -Djavax.net.ssl.keyStore="$KEYSTORE" \ + -Djavax.net.ssl.keyStorePassword="$KEYSTORE_PASSWD" \ + -Djavax.net.ssl.trustStore="$TRUSTSTORE" \ + -Djavax.net.ssl.trustStorePassword="$TRUSTSTORE_PASSWD" \ + -Dlogback.configurationFile=$PDP_SIM_HOME/etc/logback.xml \ + org.onap.policy.models.sim.pdp.PdpSimulatorMain \ + -c $CONFIG_FILE -p $PROPERTIES_FILE diff --git a/models-sim/policy-models-sim-pdp/src/main/package/tarball/assembly.xml b/models-sim/policy-models-sim-pdp/src/main/package/tarball/assembly.xml new file mode 100644 index 000000000..25ffc65a9 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/package/tarball/assembly.xml @@ -0,0 +1,68 @@ + + + + tarball + + tar.gz + + false + + + true + /lib + false + runtime + + *:jar + + + + + + ${project.basedir}/src/main/resources + + + logback.xml + + etc + unix + + + ${project.basedir}/src/main/resources/config + + + OnapPfConfig.json + topic.properties + + etc/config + unix + + + ${project.basedir}/src/main/resources/ssl + + + policy* + + etc/ssl + keep + + + diff --git a/models-sim/policy-models-sim-pdp/src/main/resources/config/OnapPfConfig.json b/models-sim/policy-models-sim-pdp/src/main/resources/config/OnapPfConfig.json new file mode 100644 index 000000000..ff7903c78 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/resources/config/OnapPfConfig.json @@ -0,0 +1,9 @@ +{ + "name":"OnapPfParameterGroup", + "pdpStatusParameters":{ + "timeIntervalMs": 120000, + "pdpType":"apex", + "description":"Pdp Heartbeat", + "supportedPolicyTypes":[{"name":"onap.policies.controlloop.operational.Apex","version":"1.0.0"}] + } +} \ No newline at end of file diff --git a/models-sim/policy-models-sim-pdp/src/main/resources/config/topic.properties b/models-sim/policy-models-sim-pdp/src/main/resources/config/topic.properties new file mode 100644 index 000000000..0139bb38a --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/resources/config/topic.properties @@ -0,0 +1,22 @@ +# ============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========================================================= + +dmaap.source.topics=POLICY-PDP-PAP +dmaap.sink.topics=POLICY-PDP-PAP +dmaap.source.topics.POLICY-PDP-PAP.servers= message-router:3904 +dmaap.sink.topics.POLICY-PDP-PAP.servers= message-router:3904 \ No newline at end of file diff --git a/models-sim/policy-models-sim-pdp/src/main/resources/logback.xml b/models-sim/policy-models-sim-pdp/src/main/resources/logback.xml new file mode 100644 index 000000000..2b650d84c --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/resources/logback.xml @@ -0,0 +1,46 @@ + + + + + DMaaPSim + + + + + + + %d %contextName [%t] %level %logger{36} - %msg%n + + + + + + + + + + + + + + + + diff --git a/models-sim/policy-models-sim-pdp/src/main/resources/ssl/policy-keystore b/models-sim/policy-models-sim-pdp/src/main/resources/ssl/policy-keystore new file mode 100644 index 000000000..7d2b1ecce Binary files /dev/null and b/models-sim/policy-models-sim-pdp/src/main/resources/ssl/policy-keystore differ diff --git a/models-sim/policy-models-sim-pdp/src/main/resources/ssl/policy-truststore b/models-sim/policy-models-sim-pdp/src/main/resources/ssl/policy-truststore new file mode 100644 index 000000000..8834ac257 Binary files /dev/null and b/models-sim/policy-models-sim-pdp/src/main/resources/ssl/policy-truststore differ diff --git a/models-sim/policy-models-sim-pdp/src/main/resources/version.txt b/models-sim/policy-models-sim-pdp/src/main/resources/version.txt new file mode 100644 index 000000000..aec42fcca --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/main/resources/version.txt @@ -0,0 +1,4 @@ +ONAP Policy-PDP simulator Service +Version: ${project.version} +Built (UTC): ${maven.build.timestamp} +ONAP https://wiki.onap.org \ No newline at end of file diff --git a/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/TestPdpSimulatorActivator.java b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/TestPdpSimulatorActivator.java new file mode 100644 index 000000000..e75bb6d26 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/TestPdpSimulatorActivator.java @@ -0,0 +1,117 @@ +/*- + * ============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.models.sim.pdp; + +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.FileInputStream; +import java.util.Properties; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.pdp.concepts.PdpStatus; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; +import org.onap.policy.models.sim.pdp.parameters.CommonTestData; +import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterGroup; +import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterHandler; + +/** + * Class to perform unit test of {@link PdpSimulatorActivator}}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestPdpSimulatorActivator { + + private PdpSimulatorActivator activator; + + /** + * Initializes an activator. + * + * @throws Exception if an error occurs + */ + @Before + public void setUp() throws Exception { + Registry.newRegistry(); + final String[] pdpSimulatorConfigParameters = { "-c", "src/test/resources/PdpSimulatorConfigParameters.json", + "-p", "src/test/resources/topic.properties" }; + final PdpSimulatorCommandLineArguments arguments = + new PdpSimulatorCommandLineArguments(pdpSimulatorConfigParameters); + final PdpSimulatorParameterGroup parGroup = new PdpSimulatorParameterHandler().getParameters(arguments); + + final Properties props = new Properties(); + final String propFile = arguments.getFullPropertyFilePath(); + try (FileInputStream stream = new FileInputStream(propFile)) { + props.load(stream); + } + + activator = new PdpSimulatorActivator(parGroup, props); + } + + /** + * Method for cleanup after each test. + * + * @throws Exception if an error occurs + */ + @After + public void teardown() throws Exception { + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } + + @Test + public void testPdpSimulatorActivator() throws PdpSimulatorException { + assertFalse(activator.isAlive()); + activator.initialize(); + assertTrue(activator.isAlive()); + assertTrue(activator.getParameterGroup().isValid()); + assertEquals(CommonTestData.PDP_SIMULATOR_GROUP_NAME, activator.getParameterGroup().getName()); + + // ensure items were added to the registry + assertNotNull(Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class)); + + // repeat - should throw an exception + assertThatIllegalStateException().isThrownBy(() -> activator.initialize()); + assertTrue(activator.isAlive()); + assertTrue(activator.getParameterGroup().isValid()); + } + + @Test + public void testTerminate() throws Exception { + activator.initialize(); + activator.terminate(); + assertFalse(activator.isAlive()); + + // ensure items have been removed from the registry + assertNull(Registry.getOrDefault(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class, null)); + + // repeat - should throw an exception + assertThatIllegalStateException().isThrownBy(() -> activator.terminate()); + assertFalse(activator.isAlive()); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/TestPdpSimulatorConstants.java b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/TestPdpSimulatorConstants.java new file mode 100644 index 000000000..2bec22af3 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/TestPdpSimulatorConstants.java @@ -0,0 +1,37 @@ +/*- + * ============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.models.sim.pdp; + +import org.junit.Test; +import org.powermock.reflect.Whitebox; + +/** + * Class to perform unit test of {@link PdpSimulatorConstants}}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestPdpSimulatorConstants { + @Test + public void test() throws Exception { + // verify that constructor does not throw an exception + Whitebox.invokeConstructor(PdpSimulatorConstants.class); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/TestPdpSimulatorMain.java b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/TestPdpSimulatorMain.java new file mode 100644 index 000000000..7a3239891 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/TestPdpSimulatorMain.java @@ -0,0 +1,106 @@ +/*- + * ============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.models.sim.pdp; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; +import org.onap.policy.models.sim.pdp.parameters.CommonTestData; + +/** + * Class to perform unit test of {@link PdpSimulatorMain}}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestPdpSimulatorMain { + private PdpSimulatorMain pdpSimulator; + + /** + * Set up. + */ + @Before + public void setUp() { + Registry.newRegistry(); + } + + /** + * Shuts "main" down. + * + * @throws Exception if an error occurs + */ + @After + public void tearDown() throws Exception { + // shut down activator + final PdpSimulatorActivator activator = Registry.getOrDefault(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR, + PdpSimulatorActivator.class, null); + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } + + @Test + public void testPdpSimulator() throws PdpSimulatorException { + final String[] pdpSimulatorConfigParameters = { "-c", "src/test/resources/PdpSimulatorConfigParameters.json", + "-p", "src/test/resources/topic.properties" }; + pdpSimulator = new PdpSimulatorMain(pdpSimulatorConfigParameters); + assertTrue(pdpSimulator.getParameters().isValid()); + assertEquals(CommonTestData.PDP_SIMULATOR_GROUP_NAME, pdpSimulator.getParameters().getName()); + + // ensure items were added to the registry + assertNotNull(Registry.get(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR, PdpSimulatorActivator.class)); + + pdpSimulator.shutdown(); + } + + @Test + public void testPdpSimulator_NoArguments() { + final String[] pdpSimulatorConfigParameters = {}; + pdpSimulator = new PdpSimulatorMain(pdpSimulatorConfigParameters); + assertTrue(pdpSimulator.getParameters() == null); + } + + @Test + public void testPdpSimulator_InvalidArguments() { + final String[] pdpSimulatorConfigParameters = { "src/test/resourcesPdpSimulatorConfigParameters.json" }; + pdpSimulator = new PdpSimulatorMain(pdpSimulatorConfigParameters); + assertTrue(pdpSimulator.getParameters() == null); + } + + @Test + public void testPdpSimulator_Help() { + final String[] pdpSimulatorConfigParameters = { "-h" }; + PdpSimulatorMain.main(pdpSimulatorConfigParameters); + } + + @Test + public void testPdpSimulator_InvalidParameters() { + final String[] pdpSimulatorConfigParameters = + { "-c", "src/test/resources/PdpSimulatorConfigParameters_InvalidName.json" }; + pdpSimulator = new PdpSimulatorMain(pdpSimulatorConfigParameters); + assertTrue(pdpSimulator.getParameters() == null); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/comm/TestPdpStateChangeListener.java b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/comm/TestPdpStateChangeListener.java new file mode 100644 index 000000000..8e3582e21 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/comm/TestPdpStateChangeListener.java @@ -0,0 +1,180 @@ +/*- + * ============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.models.sim.pdp.comm; + +import static org.junit.Assert.assertEquals; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.pdp.concepts.PdpStateChange; +import org.onap.policy.models.pdp.concepts.PdpStatus; +import org.onap.policy.models.pdp.concepts.PdpUpdate; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.sim.pdp.PdpSimulatorActivator; +import org.onap.policy.models.sim.pdp.PdpSimulatorCommandLineArguments; +import org.onap.policy.models.sim.pdp.PdpSimulatorConstants; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; +import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterGroup; +import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterHandler; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; + +/** + * Class to perform unit test of {@link PdpStateChangeListener}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestPdpStateChangeListener { + private PdpUpdateListener pdpUpdateMessageListener; + private PdpStateChangeListener pdpStateChangeListener; + private static final CommInfrastructure INFRA = CommInfrastructure.NOOP; + private static final String TOPIC = "my-topic"; + private PdpSimulatorActivator activator; + + /** + * Method for setup before each test. + * + * @throws PdpSimulatorException if some error occurs while starting up the pdp simulator + * @throws FileNotFoundException if the file is missing + * @throws IOException if IO exception occurs + */ + @Before + public void setUp() throws PdpSimulatorException, FileNotFoundException, IOException { + pdpUpdateMessageListener = new PdpUpdateListener(); + pdpStateChangeListener = new PdpStateChangeListener(); + Registry.newRegistry(); + final String[] pdpSimulatorConfigParameters = { "-c", "src/test/resources/PdpSimulatorConfigParameters.json", + "-p", "src/test/resources/topic.properties" }; + final PdpSimulatorCommandLineArguments arguments = new PdpSimulatorCommandLineArguments(); + PdpSimulatorParameterGroup pdpSimulatorParameterGroup; + // The arguments return a string if there is a message to print and we should + // exit + final String argumentMessage = arguments.parse(pdpSimulatorConfigParameters); + if (argumentMessage != null) { + return; + } + // Validate that the arguments are sane + arguments.validate(); + + // Read the parameters + pdpSimulatorParameterGroup = new PdpSimulatorParameterHandler().getParameters(arguments); + + // Read the properties + final Properties topicProperties = new Properties(); + final String propFile = arguments.getFullPropertyFilePath(); + try (FileInputStream stream = new FileInputStream(propFile)) { + topicProperties.load(stream); + } + activator = new PdpSimulatorActivator(pdpSimulatorParameterGroup, topicProperties); + Registry.register(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR, activator); + activator.initialize(); + } + + /** + * Method for cleanup after each test. + * + * @throws Exception if an error occurs + */ + @After + public void teardown() throws Exception { + + // clear the pdp simulator activator + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } + + /** + * Method to initiate a PdpUpdate. + * + * @param instance the instance id + * @return PdpUpdate the pdp update message + */ + private PdpUpdate performPdpUpdate(final String instance) { + final PdpUpdate pdpUpdateMsg = new PdpUpdate(); + pdpUpdateMsg.setDescription("dummy pdp status for test"); + pdpUpdateMsg.setPdpGroup("pdpGroup"); + pdpUpdateMsg.setPdpSubgroup("pdpSubgroup"); + pdpUpdateMsg.setName(instance); + final ToscaPolicy toscaPolicy = new ToscaPolicy(); + toscaPolicy.setType("apexpolicytype"); + toscaPolicy.setVersion("1.0"); + final Map propertiesMap = new LinkedHashMap<>(); + + String properties; + try { + properties = new String(Files.readAllBytes(Paths.get("src\\test\\resources\\dummyProperties.json")), + StandardCharsets.UTF_8); + propertiesMap.put("content", properties); + } catch (final IOException e) { + propertiesMap.put("content", ""); + } + toscaPolicy.setProperties(propertiesMap); + final List toscaPolicies = new ArrayList(); + toscaPolicies.add(toscaPolicy); + pdpUpdateMsg.setPolicies(toscaPolicies); + pdpUpdateMessageListener.onTopicEvent(INFRA, TOPIC, null, pdpUpdateMsg); + return pdpUpdateMsg; + } + + @Test + public void testPdpStateChangeMessageListener_passivetopassive() { + final PdpStatus pdpStatus = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT); + performPdpUpdate(pdpStatus.getName()); + final PdpStateChange pdpStateChangeMsg = new PdpStateChange(); + pdpStateChangeMsg.setState(PdpState.PASSIVE); + pdpStateChangeMsg.setPdpGroup("pdpGroup"); + pdpStateChangeMsg.setPdpSubgroup("pdpSubgroup"); + pdpStateChangeMsg.setName(pdpStatus.getName()); + pdpStateChangeListener.onTopicEvent(INFRA, TOPIC, null, pdpStateChangeMsg); + + assertEquals(pdpStatus.getState(), pdpStateChangeMsg.getState()); + } + + @Test + public void testPdpStateChangeMessageListener_activetoactive() { + final PdpStatus pdpStatus = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT); + performPdpUpdate(pdpStatus.getName()); + pdpStatus.setState(PdpState.ACTIVE); + final PdpStateChange pdpStateChangeMsg = new PdpStateChange(); + pdpStateChangeMsg.setState(PdpState.ACTIVE); + pdpStateChangeMsg.setPdpGroup("pdpGroup"); + pdpStateChangeMsg.setPdpSubgroup("pdpSubgroup"); + pdpStateChangeMsg.setName(pdpStatus.getName()); + pdpStateChangeListener.onTopicEvent(INFRA, TOPIC, null, pdpStateChangeMsg); + + assertEquals(pdpStatus.getState(), pdpStateChangeMsg.getState()); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/comm/TestPdpUpdateListener.java b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/comm/TestPdpUpdateListener.java new file mode 100644 index 000000000..f3885f42d --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/comm/TestPdpUpdateListener.java @@ -0,0 +1,148 @@ +/*- + * ============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.models.sim.pdp.comm; + +import static org.junit.Assert.assertEquals; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.pdp.concepts.PdpStatus; +import org.onap.policy.models.pdp.concepts.PdpUpdate; +import org.onap.policy.models.sim.pdp.PdpSimulatorActivator; +import org.onap.policy.models.sim.pdp.PdpSimulatorCommandLineArguments; +import org.onap.policy.models.sim.pdp.PdpSimulatorConstants; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; +import org.onap.policy.models.sim.pdp.handler.PdpMessageHandler; +import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterGroup; +import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterHandler; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; + +/** + * Class to perform unit test of {@link PdpUpdateListener}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestPdpUpdateListener { + private PdpUpdateListener pdpUpdateMessageListener; + private static final CommInfrastructure INFRA = CommInfrastructure.NOOP; + private static final String TOPIC = "my-topic"; + private PdpSimulatorActivator activator; + + /** + * Method for setup before each test. + * + * @throws PdpSimulatorException if some error occurs while starting up the pdp simulator + * @throws FileNotFoundException if the file is missing + * @throws IOException if IO exception occurs + */ + @Before + public void setUp() throws PdpSimulatorException, FileNotFoundException, IOException { + Registry.newRegistry(); + final String[] pdpSimulatorConfigParameters = { "-c", "src/test/resources/PdpSimulatorConfigParameters.json", + "-p", "src/test/resources/topic.properties" }; + final PdpSimulatorCommandLineArguments arguments = new PdpSimulatorCommandLineArguments(); + PdpSimulatorParameterGroup pdpSimulatorParameterGroup; + // The arguments return a string if there is a message to print and we should + // exit + final String argumentMessage = arguments.parse(pdpSimulatorConfigParameters); + if (argumentMessage != null) { + return; + } + // Validate that the arguments are sane + arguments.validate(); + + // Read the parameters + pdpSimulatorParameterGroup = new PdpSimulatorParameterHandler().getParameters(arguments); + + // Read the properties + final Properties topicProperties = new Properties(); + final String propFile = arguments.getFullPropertyFilePath(); + try (FileInputStream stream = new FileInputStream(propFile)) { + topicProperties.load(stream); + } + activator = new PdpSimulatorActivator(pdpSimulatorParameterGroup, topicProperties); + Registry.register(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR, activator); + activator.initialize(); + pdpUpdateMessageListener = new PdpUpdateListener(); + } + + /** + * Method for cleanup after each test. + * + * @throws Exception if an error occurs + */ + @After + public void teardown() throws Exception { + + // clear the pdp simulator activator + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } + + @Test + public void testPdpUpdateMssageListener() { + final PdpStatus pdpStatus = Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT); + final PdpUpdate pdpUpdateMsg = new PdpUpdate(); + pdpUpdateMsg.setDescription("dummy pdp status for test"); + pdpUpdateMsg.setPdpGroup("pdpGroup"); + pdpUpdateMsg.setPdpSubgroup("pdpSubgroup"); + pdpUpdateMsg.setName(pdpStatus.getName()); + pdpUpdateMsg.setPdpHeartbeatIntervalMs(Long.valueOf(3000)); + final ToscaPolicy toscaPolicy = new ToscaPolicy(); + toscaPolicy.setType("apexpolicytype"); + toscaPolicy.setVersion("1.0"); + toscaPolicy.setName("apex policy name"); + final Map propertiesMap = new LinkedHashMap<>(); + String properties; + try { + properties = new String(Files.readAllBytes(Paths.get("src\\test\\resources\\dummyProperties.json")), + StandardCharsets.UTF_8); + propertiesMap.put("content", properties); + } catch (final IOException e) { + propertiesMap.put("content", ""); + } + toscaPolicy.setProperties(propertiesMap); + final List toscaPolicies = new ArrayList(); + toscaPolicies.add(toscaPolicy); + pdpUpdateMsg.setPolicies(toscaPolicies); + pdpUpdateMessageListener.onTopicEvent(INFRA, TOPIC, null, pdpUpdateMsg); + assertEquals(pdpStatus.getPdpGroup(), pdpUpdateMsg.getPdpGroup()); + assertEquals(pdpStatus.getPdpSubgroup(), pdpUpdateMsg.getPdpSubgroup()); + assertEquals(pdpStatus.getPolicies(), + new PdpMessageHandler().getToscaPolicyIdentifiers(pdpUpdateMsg.getPolicies())); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/exception/TestExceptions.java b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/exception/TestExceptions.java new file mode 100644 index 000000000..45845a941 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/exception/TestExceptions.java @@ -0,0 +1,38 @@ +/*- + * ============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.models.sim.pdp.exception; + +import org.junit.Test; +import org.onap.policy.common.utils.test.ExceptionsTester; + +/** + * Class to perform unit test of {@link PdpSimulatorException PdpSimulatorRunTimeException}}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestExceptions { + + @Test + public void test() { + new ExceptionsTester().test(PdpSimulatorException.class); + new ExceptionsTester().test(PdpSimulatorRunTimeException.class); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/CommonTestData.java b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/CommonTestData.java new file mode 100644 index 000000000..4351645b8 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/CommonTestData.java @@ -0,0 +1,144 @@ +/*- + * ============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.models.sim.pdp.parameters; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; + +/** + * Class to hold/create all parameters for test cases. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class CommonTestData { + + public static final String PDP_SIMULATOR_GROUP_NAME = "PdpSimulatorParameterGroup"; + public static final long TIME_INTERVAL = 2000; + public static final String PDP_NAME = "apex-pdp"; + public static final String VERSION = "0.0.1"; + public static final String PDP_TYPE = "apex"; + public static final String DESCRIPTION = "Pdp status for HealthCheck"; + public static final String POLICY_NAME = "onap.controllloop.operational.apex.BBS"; + public static final String POLICY_VERSION = "0.0.1"; + public static final List SUPPORTED_POLICY_TYPES = + Arrays.asList(getSupportedPolicyTypes(POLICY_NAME, POLICY_VERSION)); + private static final String REST_SERVER_PASSWORD = "zb!XztG34"; + private static final String REST_SERVER_USER = "healthcheck"; + private static final int REST_SERVER_PORT = 6969; + private static final String REST_SERVER_HOST = "0.0.0.0"; + private static final boolean REST_SERVER_HTTPS = true; + private static final boolean REST_SERVER_AAF = false; + + public static final Coder coder = new StandardCoder(); + + /** + * Returns supported policy types for test cases. + * + * @return supported policy types + */ + public static ToscaPolicyTypeIdentifierParameters getSupportedPolicyTypes(final String name, final String version) { + final ToscaPolicyTypeIdentifierParameters policyTypeIdentParameters = new ToscaPolicyTypeIdentifierParameters(); + policyTypeIdentParameters.setName(name); + policyTypeIdentParameters.setVersion(version); + return policyTypeIdentParameters; + } + + /** + * Converts the contents of a map to a parameter class. + * + * @param source property map + * @param clazz class of object to be created from the map + * @return a new object represented by the map + */ + public T toObject(final Map source, final Class clazz) { + try { + return coder.decode(coder.encode(source), clazz); + + } catch (final CoderException e) { + throw new RuntimeException("cannot create " + clazz.getName() + " from map", e); + } + } + + /** + * Returns a property map for a PdpSimulatorParameterGroup map for test cases. + * + * @param name name of the parameters + * + * @return a property map suitable for constructing an object + */ + public Map getPdpSimulatorParameterGroupMap(final String name) { + final Map map = new TreeMap<>(); + + map.put("name", name); + map.put("restServerParameters", getRestServerParametersMap(false)); + map.put("pdpStatusParameters", getPdpStatusParametersMap(false)); + + return map; + } + + /** + * Returns a property map for a RestServerParameters map for test cases. + * + * @param isEmpty boolean value to represent that object created should be empty or not + * @return a property map suitable for constructing an object + */ + public Map getRestServerParametersMap(final boolean isEmpty) { + final Map map = new TreeMap<>(); + map.put("https", REST_SERVER_HTTPS); + map.put("aaf", REST_SERVER_AAF); + + if (!isEmpty) { + map.put("host", REST_SERVER_HOST); + map.put("port", REST_SERVER_PORT); + map.put("userName", REST_SERVER_USER); + map.put("password", REST_SERVER_PASSWORD); + } + + return map; + } + + /** + * Returns a property map for a PdpStatusParameters map for test cases. + * + * @param isEmpty boolean value to represent that object created should be empty or not + * @return a property map suitable for constructing an object + */ + public Map getPdpStatusParametersMap(final boolean isEmpty) { + final Map map = new TreeMap<>(); + if (!isEmpty) { + map.put("timeIntervalMs", TIME_INTERVAL); + map.put("pdpName", PDP_NAME); + map.put("version", VERSION); + map.put("pdpType", PDP_TYPE); + map.put("description", DESCRIPTION); + map.put("supportedPolicyTypes", SUPPORTED_POLICY_TYPES); + } + + return map; + } +} diff --git a/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/TestPdpSimulatorParameterGroup.java b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/TestPdpSimulatorParameterGroup.java new file mode 100644 index 000000000..b4a54b8ae --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/TestPdpSimulatorParameterGroup.java @@ -0,0 +1,107 @@ +/*- + * ============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.models.sim.pdp.parameters; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Map; + +import org.junit.Test; +import org.onap.policy.common.parameters.GroupValidationResult; + +/** + * Class to perform unit test of {@link PdpSimulatorParameterGroup}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestPdpSimulatorParameterGroup { + CommonTestData commonTestData = new CommonTestData(); + + @Test + public void testPdpSimulatorParameterGroup_Named() { + final PdpSimulatorParameterGroup pdpSimulatorParameters = new PdpSimulatorParameterGroup("my-name"); + assertEquals("my-name", pdpSimulatorParameters.getName()); + } + + @Test + public void testPdpSimulatorParameterGroup() { + final PdpSimulatorParameterGroup pdpSimulatorParameters = commonTestData.toObject( + commonTestData.getPdpSimulatorParameterGroupMap(CommonTestData.PDP_SIMULATOR_GROUP_NAME), + PdpSimulatorParameterGroup.class); + final PdpStatusParameters pdpStatusParameters = pdpSimulatorParameters.getPdpStatusParameters(); + final GroupValidationResult validationResult = pdpSimulatorParameters.validate(); + assertTrue(validationResult.isValid()); + assertEquals(CommonTestData.PDP_SIMULATOR_GROUP_NAME, pdpSimulatorParameters.getName()); + assertEquals(CommonTestData.TIME_INTERVAL, pdpStatusParameters.getTimeIntervalMs()); + assertEquals(CommonTestData.PDP_TYPE, pdpStatusParameters.getPdpType()); + assertEquals(CommonTestData.DESCRIPTION, pdpStatusParameters.getDescription()); + assertEquals(CommonTestData.SUPPORTED_POLICY_TYPES, pdpStatusParameters.getSupportedPolicyTypes()); + } + + @Test + public void testPdpSimulatorParameterGroup_NullName() { + final PdpSimulatorParameterGroup pdpSimulatorParameters = commonTestData + .toObject(commonTestData.getPdpSimulatorParameterGroupMap(null), PdpSimulatorParameterGroup.class); + final GroupValidationResult validationResult = pdpSimulatorParameters.validate(); + assertFalse(validationResult.isValid()); + assertEquals(null, pdpSimulatorParameters.getName()); + assertTrue(validationResult.getResult().contains("is null")); + } + + @Test + public void testPdpSimulatorParameterGroup_EmptyName() { + final PdpSimulatorParameterGroup pdpSimulatorParameters = commonTestData + .toObject(commonTestData.getPdpSimulatorParameterGroupMap(""), PdpSimulatorParameterGroup.class); + final GroupValidationResult validationResult = pdpSimulatorParameters.validate(); + assertFalse(validationResult.isValid()); + assertEquals("", pdpSimulatorParameters.getName()); + assertTrue(validationResult.getResult().contains( + "field \"name\" type \"java.lang.String\" value \"\" INVALID, " + "must be a non-blank string")); + } + + @Test + public void testPdpSimulatorParameterGroup_SetName() { + final PdpSimulatorParameterGroup pdpSimulatorParameters = commonTestData.toObject( + commonTestData.getPdpSimulatorParameterGroupMap(CommonTestData.PDP_SIMULATOR_GROUP_NAME), + PdpSimulatorParameterGroup.class); + pdpSimulatorParameters.setName("PdpSimulatorNewGroup"); + final GroupValidationResult validationResult = pdpSimulatorParameters.validate(); + assertTrue(validationResult.isValid()); + assertEquals("PdpSimulatorNewGroup", pdpSimulatorParameters.getName()); + } + + @Test + public void testPdpSimulatorParameterGroup_EmptyPdpStatusParameters() { + final Map map = + commonTestData.getPdpSimulatorParameterGroupMap(CommonTestData.PDP_SIMULATOR_GROUP_NAME); + map.put("pdpStatusParameters", commonTestData.getPdpStatusParametersMap(true)); + final PdpSimulatorParameterGroup pdpSimulatorParameters = + commonTestData.toObject(map, PdpSimulatorParameterGroup.class); + final GroupValidationResult validationResult = pdpSimulatorParameters.validate(); + assertFalse(validationResult.isValid()); + assertTrue(validationResult.getResult() + .contains("\"org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterGroup\" INVALID, " + + "parameter group has status INVALID")); + } + +} diff --git a/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/TestPdpSimulatorParameterHandler.java b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/TestPdpSimulatorParameterHandler.java new file mode 100644 index 000000000..e8e1f9036 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/TestPdpSimulatorParameterHandler.java @@ -0,0 +1,157 @@ +/*- + * ============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.models.sim.pdp.parameters; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.FileNotFoundException; + +import org.junit.Test; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.models.sim.pdp.PdpSimulatorCommandLineArguments; +import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException; + +/** + * Class to perform unit test of {@link PdpSimulatorParameterHandler}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestPdpSimulatorParameterHandler { + + @Test + public void testParameterHandlerNoParameterFile() throws PdpSimulatorException { + final String[] emptyArgumentString = { "-c", "src/test/resources/NoParametersFile.json" }; + + final PdpSimulatorCommandLineArguments emptyArguments = new PdpSimulatorCommandLineArguments(); + emptyArguments.parse(emptyArgumentString); + + try { + new PdpSimulatorParameterHandler().getParameters(emptyArguments); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertTrue(e.getCause() instanceof CoderException); + assertTrue(e.getCause().getCause() instanceof FileNotFoundException); + } + } + + @Test + public void testParameterHandlerEmptyParameters() throws PdpSimulatorException { + final String[] noArgumentString = { "-c", "src/test/resources/NoParameters.json" }; + + final PdpSimulatorCommandLineArguments noArguments = new PdpSimulatorCommandLineArguments(); + noArguments.parse(noArgumentString); + + try { + new PdpSimulatorParameterHandler().getParameters(noArguments); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertTrue(e.getMessage().contains("no parameters found")); + } + } + + @Test + public void testParameterHandlerInvalidParameters() throws PdpSimulatorException { + final String[] invalidArgumentString = { "-c", "src/test/resources/InvalidParameters.json" }; + + final PdpSimulatorCommandLineArguments invalidArguments = new PdpSimulatorCommandLineArguments(); + invalidArguments.parse(invalidArgumentString); + + try { + new PdpSimulatorParameterHandler().getParameters(invalidArguments); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertTrue(e.getMessage().startsWith("error reading parameters from")); + assertTrue(e.getCause() instanceof CoderException); + } + } + + @Test + public void testParameterHandlerNoParameters() throws PdpSimulatorException { + final String[] noArgumentString = { "-c", "src/test/resources/EmptyConfigParameters.json" }; + + final PdpSimulatorCommandLineArguments noArguments = new PdpSimulatorCommandLineArguments(); + noArguments.parse(noArgumentString); + + try { + new PdpSimulatorParameterHandler().getParameters(noArguments); + } catch (final Exception e) { + assertTrue(e.getMessage().contains("is null")); + } + } + + @Test + public void testPdpSimulatorParameterGroup() throws PdpSimulatorException { + final String[] pdpSimulatorConfigParameters = { "-c", "src/test/resources/PdpSimulatorConfigParameters.json" }; + + final PdpSimulatorCommandLineArguments arguments = new PdpSimulatorCommandLineArguments(); + arguments.parse(pdpSimulatorConfigParameters); + + final PdpSimulatorParameterGroup parGroup = new PdpSimulatorParameterHandler().getParameters(arguments); + assertTrue(arguments.checkSetConfigurationFilePath()); + assertEquals(CommonTestData.PDP_SIMULATOR_GROUP_NAME, parGroup.getName()); + } + + @Test + public void testPdpSimulatorParameterGroup_InvalidName() throws PdpSimulatorException { + final String[] pdpSimulatorConfigParameters = {"-c", + "src/test/resources/PdpSimulatorConfigParameters_InvalidName.json"}; + + final PdpSimulatorCommandLineArguments arguments = new PdpSimulatorCommandLineArguments(); + arguments.parse(pdpSimulatorConfigParameters); + + try { + new PdpSimulatorParameterHandler().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 testPdpSimulatorVersion() throws PdpSimulatorException { + final String[] pdpSimulatorConfigParameters = { "-v" }; + final PdpSimulatorCommandLineArguments arguments = new PdpSimulatorCommandLineArguments(); + final String version = arguments.parse(pdpSimulatorConfigParameters); + assertTrue(version.startsWith("ONAP Policy-PDP simulator Service")); + } + + @Test + public void testPdpSimulatorHelp() throws PdpSimulatorException { + final String[] pdpSimulatorConfigParameters = { "-h" }; + final PdpSimulatorCommandLineArguments arguments = new PdpSimulatorCommandLineArguments(); + final String help = arguments.parse(pdpSimulatorConfigParameters); + assertTrue(help.startsWith("usage:")); + } + + @Test + public void testPdpSimulatorInvalidOption() throws PdpSimulatorException { + final String[] pdpSimulatorConfigParameters = { "-d" }; + final PdpSimulatorCommandLineArguments arguments = new PdpSimulatorCommandLineArguments(); + try { + arguments.parse(pdpSimulatorConfigParameters); + } catch (final Exception exp) { + assertTrue(exp.getMessage().startsWith("invalid command line arguments specified")); + } + } +} diff --git a/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/TestPdpStatusParameters.java b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/TestPdpStatusParameters.java new file mode 100644 index 000000000..a48082901 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/java/org/onap/policy/models/sim/pdp/parameters/TestPdpStatusParameters.java @@ -0,0 +1,58 @@ +/*- + * ============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.models.sim.pdp.parameters; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.policy.common.parameters.GroupValidationResult; + +/** + * Class to perform unit test of {@link PdpStatusParameters}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestPdpStatusParameters { + private static CommonTestData testData = new CommonTestData(); + + @Test + public void test() throws Exception { + final PdpStatusParameters pdpStatusParameters = + testData.toObject(testData.getPdpStatusParametersMap(false), PdpStatusParameters.class); + final GroupValidationResult validationResult = pdpStatusParameters.validate(); + assertTrue(validationResult.isValid()); + assertEquals(CommonTestData.TIME_INTERVAL, pdpStatusParameters.getTimeIntervalMs()); + assertEquals(CommonTestData.PDP_TYPE, pdpStatusParameters.getPdpType()); + assertEquals(CommonTestData.DESCRIPTION, pdpStatusParameters.getDescription()); + assertEquals(CommonTestData.SUPPORTED_POLICY_TYPES, pdpStatusParameters.getSupportedPolicyTypes()); + } + + @Test + public void testValidate() throws Exception { + final PdpStatusParameters pdpStatusParameters = + testData.toObject(testData.getPdpStatusParametersMap(false), PdpStatusParameters.class); + final GroupValidationResult result = pdpStatusParameters.validate(); + assertNull(result.getResult()); + assertTrue(result.isValid()); + } +} diff --git a/models-sim/policy-models-sim-pdp/src/test/resources/EmptyConfigParameters.json b/models-sim/policy-models-sim-pdp/src/test/resources/EmptyConfigParameters.json new file mode 100644 index 000000000..7a73a41bf --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/resources/EmptyConfigParameters.json @@ -0,0 +1,2 @@ +{ +} \ No newline at end of file diff --git a/models-sim/policy-models-sim-pdp/src/test/resources/InvalidParameters.json b/models-sim/policy-models-sim-pdp/src/test/resources/InvalidParameters.json new file mode 100644 index 000000000..de2040cc8 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/resources/InvalidParameters.json @@ -0,0 +1,3 @@ +{ + "name" : [] +} \ No newline at end of file diff --git a/models-sim/policy-models-sim-pdp/src/test/resources/NoParameters.json b/models-sim/policy-models-sim-pdp/src/test/resources/NoParameters.json new file mode 100644 index 000000000..e69de29bb diff --git a/models-sim/policy-models-sim-pdp/src/test/resources/PdpSimulatorConfigParameters.json b/models-sim/policy-models-sim-pdp/src/test/resources/PdpSimulatorConfigParameters.json new file mode 100644 index 000000000..e1772c1c7 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/resources/PdpSimulatorConfigParameters.json @@ -0,0 +1,9 @@ +{ + "name":"PdpSimulatorParameterGroup", + "pdpStatusParameters":{ + "timeIntervalMs": 120000, + "pdpType":"apex", + "description":"Pdp Heartbeat", + "supportedPolicyTypes":[{"name":"onap.policies.controlloop.operational.Apex","version":"1.0.0"}] + } +} \ No newline at end of file diff --git a/models-sim/policy-models-sim-pdp/src/test/resources/PdpSimulatorConfigParameters_InvalidName.json b/models-sim/policy-models-sim-pdp/src/test/resources/PdpSimulatorConfigParameters_InvalidName.json new file mode 100644 index 000000000..0f316a32e --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/resources/PdpSimulatorConfigParameters_InvalidName.json @@ -0,0 +1,4 @@ +{ + "name":" ", + "timeIntervalMs": 5000 +} \ No newline at end of file diff --git a/models-sim/policy-models-sim-pdp/src/test/resources/PdpSimulatorConfigParameters_sim.json b/models-sim/policy-models-sim-pdp/src/test/resources/PdpSimulatorConfigParameters_sim.json new file mode 100644 index 000000000..d583b81da --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/resources/PdpSimulatorConfigParameters_sim.json @@ -0,0 +1,9 @@ +{ + "name":"PdpSimulatorParameterGroup", + "pdpStatusParameters":{ + "timeIntervalMs": 120000, + "pdpType":"apex", + "description":"Pdp Heartbeat", + "supportedPolicyTypes":[{"name":"onap.policies.controlloop.operational.Apex","version":"1.0.0"}] + } +} diff --git a/models-sim/policy-models-sim-pdp/src/test/resources/TestConfigParameters.json b/models-sim/policy-models-sim-pdp/src/test/resources/TestConfigParameters.json new file mode 100644 index 000000000..360b02095 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/resources/TestConfigParameters.json @@ -0,0 +1,9 @@ +{ + "name":"PdpSimulatorParameterGroup", + "pdpStatusParameters":{ + "timeIntervalMs": 120000, + "pdpType":"apex", + "description":"Pdp heartbeat", + "supportedPolicyTypes":[{"name":"onap.policies.controlloop.operational.Apex","version":"1.0.0"}] + } +} \ No newline at end of file diff --git a/models-sim/policy-models-sim-pdp/src/test/resources/dummyProperties.json b/models-sim/policy-models-sim-pdp/src/test/resources/dummyProperties.json new file mode 100644 index 000000000..849b86e69 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/resources/dummyProperties.json @@ -0,0 +1,43 @@ +{ + "engineServiceParameters": { + "name": "MyApexEngine", + "version": "0.0.1", + "id": 45, + "instanceCount": 2, + "deploymentPort": 65522, + "policy_type_impl": "onap.policies.controlloop.operational.apex.sampledomain.Impl", + "engineParameters": { + "executorParameters": { + "JAVASCRIPT": { + "parameterClassName": "org.onap.policy.apex.service.engine.parameters.dummyclasses.SuperDooperExecutorParameters" + } + } + } + }, + "eventOutputParameters": { + "FirstProducer": { + "carrierTechnologyParameters": { + "carrierTechnology": "FILE", + "parameters": { + "standardIo": true + } + }, + "eventProtocolParameters": { + "eventProtocol": "JSON" + } + } + }, + "eventInputParameters": { + "TheFileConsumer1": { + "carrierTechnologyParameters": { + "carrierTechnology": "FILE", + "parameters": { + "fileName": "src/test/resources/events/TestPojoEvent.json" + } + }, + "eventProtocolParameters": { + "eventProtocol": "JSON" + } + } + } +} \ No newline at end of file diff --git a/models-sim/policy-models-sim-pdp/src/test/resources/topic.properties b/models-sim/policy-models-sim-pdp/src/test/resources/topic.properties new file mode 100644 index 000000000..9f3c21dff --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/resources/topic.properties @@ -0,0 +1,22 @@ +# ============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========================================================= + +noop.sink.topics=POLICY-PDP-PAP +noop.sink.topics.POLICY-PDP-PAP.servers=anyserver +noop.source.topics=POLICY-PDP-PAP +noop.source.topics.POLICY-PDP-PAP.servers=anyserver \ No newline at end of file diff --git a/models-sim/policy-models-sim-pdp/src/test/resources/topic_sim.properties b/models-sim/policy-models-sim-pdp/src/test/resources/topic_sim.properties new file mode 100644 index 000000000..2bdf8c7b1 --- /dev/null +++ b/models-sim/policy-models-sim-pdp/src/test/resources/topic_sim.properties @@ -0,0 +1,22 @@ +# ============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========================================================= + +dmaap.sink.topics=POLICY-PDP-PAP +dmaap.sink.topics.POLICY-PDP-PAP.servers=localhost:6845 +dmaap.source.topics=POLICY-PDP-PAP +dmaap.source.topics.POLICY-PDP-PAP.servers=localhost:6845 diff --git a/models-sim/pom.xml b/models-sim/pom.xml index c6165cc16..6c8e4ae16 100644 --- a/models-sim/pom.xml +++ b/models-sim/pom.xml @@ -32,5 +32,6 @@ ${project.artifactId} models-sim-dmaap + policy-models-sim-pdp -- cgit 1.2.3-korg