From eabc69580026cad20f2ea5448f6cc7e604359d1f Mon Sep 17 00:00:00 2001 From: "a.sreekumar" Date: Thu, 11 Apr 2019 16:56:29 +0000 Subject: Changes for packaging services-onappf and some refactoring 1) Added the code for packaging PDP-A. 2) Updating the package names. 3) Updating the dependencies in services-onappf. Some dependencies can be removed as they are brought in while packaging. 4) Some other minor changes. Change-Id: Idf62d7854f3435806a9e8aa975138fbfd45e3ea8 Issue-ID: POLICY-1632 Signed-off-by: a.sreekumar --- packages/apex-pdp-package-full/pom.xml | 15 +- .../src/main/package/scripts/apexApps.bat | 2 + .../src/main/package/scripts/apexApps.sh | 2 + .../src/main/package/scripts/apexOnapPf.bat | 52 ++++ .../src/main/package/scripts/apexOnapPf.sh | 67 +++++ services/services-onappf/pom.xml | 137 ++-------- .../apex/services/onappf/ApexStarterActivator.java | 203 ++++++++++++++ .../onappf/ApexStarterCommandLineArguments.java | 299 +++++++++++++++++++++ .../apex/services/onappf/ApexStarterConstants.java | 34 +++ .../apex/services/onappf/ApexStarterMain.java | 165 ++++++++++++ .../onappf/comm/PdpStateChangeListener.java | 52 ++++ .../services/onappf/comm/PdpStatusPublisher.java | 92 +++++++ .../services/onappf/comm/PdpUpdateListener.java | 54 ++++ .../onappf/exception/ApexStarterException.java | 59 ++++ .../exception/ApexStarterRunTimeException.java | 58 ++++ .../services/onappf/handler/ApexEngineHandler.java | 110 ++++++++ .../services/onappf/handler/PdpMessageHandler.java | 152 +++++++++++ .../handler/PdpStateChangeMessageHandler.java | 138 ++++++++++ .../onappf/handler/PdpUpdateMessageHandler.java | 163 +++++++++++ .../parameters/ApexStarterParameterGroup.java | 49 ++++ .../parameters/ApexStarterParameterHandler.java | 88 ++++++ .../onappf/parameters/PdpStatusParameters.java | 52 ++++ .../ToscaPolicyTypeIdentifierParameters.java | 43 +++ .../policy/apex/starter/ApexStarterActivator.java | 201 -------------- .../starter/ApexStarterCommandLineArguments.java | 299 --------------------- .../policy/apex/starter/ApexStarterConstants.java | 34 --- .../onap/policy/apex/starter/ApexStarterMain.java | 165 ------------ .../apex/starter/comm/PdpStateChangeListener.java | 52 ---- .../apex/starter/comm/PdpStatusPublisher.java | 92 ------- .../apex/starter/comm/PdpUpdateListener.java | 54 ---- .../apex/starter/engine/ApexEngineHandler.java | 110 -------- .../starter/exception/ApexStarterException.java | 59 ---- .../exception/ApexStarterRunTimeException.java | 58 ---- .../apex/starter/handler/PdpMessageHandler.java | 152 ----------- .../handler/PdpStateChangeMessageHandler.java | 139 ---------- .../starter/handler/PdpUpdateMessageHandler.java | 164 ----------- .../parameters/ApexStarterParameterGroup.java | 49 ---- .../parameters/ApexStarterParameterHandler.java | 88 ------ .../starter/parameters/PdpStatusParameters.java | 52 ---- .../ToscaPolicyTypeIdentifierParameters.java | 43 --- .../src/main/resources/config/OnapPfConfig.json | 9 + .../src/main/resources/config/topic.properties | 23 ++ .../services/onappf/TestApexStarterActivator.java | 120 +++++++++ .../services/onappf/TestApexStarterConstants.java | 38 +++ .../apex/services/onappf/TestApexStarterMain.java | 109 ++++++++ .../onappf/comm/TestPdpStateChangeListener.java | 173 ++++++++++++ .../onappf/comm/TestPdpUpdateListener.java | 142 ++++++++++ .../services/onappf/exception/TestExceptions.java | 40 +++ .../services/onappf/parameters/CommonTestData.java | 117 ++++++++ .../parameters/TestApexStarterParameterGroup.java | 106 ++++++++ .../TestApexStarterParameterHandler.java | 159 +++++++++++ .../onappf/parameters/TestPdpStatusParameters.java | 59 ++++ .../apex/starter/TestApexStarterActivator.java | 117 -------- .../apex/starter/TestApexStarterConstants.java | 37 --- .../policy/apex/starter/TestApexStarterMain.java | 106 -------- .../starter/comm/TestPdpStateChangeListener.java | 171 ------------ .../apex/starter/comm/TestPdpUpdateListener.java | 141 ---------- .../apex/starter/exception/TestExceptions.java | 38 --- .../apex/starter/parameters/CommonTestData.java | 116 -------- .../parameters/TestApexStarterParameterGroup.java | 106 -------- .../TestApexStarterParameterHandler.java | 157 ----------- .../parameters/TestPdpStatusParameters.java | 58 ---- .../resources/ApexStarterConfigParameters.json | 7 +- .../src/test/resources/topic.properties | 18 ++ 64 files changed, 3079 insertions(+), 2985 deletions(-) create mode 100644 packages/apex-pdp-package-full/src/main/package/scripts/apexOnapPf.bat create mode 100644 packages/apex-pdp-package-full/src/main/package/scripts/apexOnapPf.sh create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterActivator.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterCommandLineArguments.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterConstants.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterMain.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/comm/PdpStateChangeListener.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/comm/PdpStatusPublisher.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/comm/PdpUpdateListener.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/exception/ApexStarterException.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/exception/ApexStarterRunTimeException.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/ApexEngineHandler.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpMessageHandler.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpStateChangeMessageHandler.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpUpdateMessageHandler.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/ApexStarterParameterGroup.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/ApexStarterParameterHandler.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/PdpStatusParameters.java create mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/ToscaPolicyTypeIdentifierParameters.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterActivator.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterCommandLineArguments.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterConstants.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterMain.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/comm/PdpStateChangeListener.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/comm/PdpStatusPublisher.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/comm/PdpUpdateListener.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/engine/ApexEngineHandler.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/exception/ApexStarterException.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/exception/ApexStarterRunTimeException.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/handler/PdpMessageHandler.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/handler/PdpStateChangeMessageHandler.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/handler/PdpUpdateMessageHandler.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/ApexStarterParameterGroup.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/ApexStarterParameterHandler.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/PdpStatusParameters.java delete mode 100644 services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/ToscaPolicyTypeIdentifierParameters.java create mode 100644 services/services-onappf/src/main/resources/config/OnapPfConfig.json create mode 100644 services/services-onappf/src/main/resources/config/topic.properties create mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterActivator.java create mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterConstants.java create mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterMain.java create mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpStateChangeListener.java create mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpUpdateListener.java create mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/exception/TestExceptions.java create mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/CommonTestData.java create mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterGroup.java create mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterHandler.java create mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestPdpStatusParameters.java delete mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/starter/TestApexStarterActivator.java delete mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/starter/TestApexStarterConstants.java delete mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/starter/TestApexStarterMain.java delete mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/starter/comm/TestPdpStateChangeListener.java delete mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/starter/comm/TestPdpUpdateListener.java delete mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/starter/exception/TestExceptions.java delete mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/CommonTestData.java delete mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/TestApexStarterParameterGroup.java delete mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/TestApexStarterParameterHandler.java delete mode 100644 services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/TestPdpStatusParameters.java diff --git a/packages/apex-pdp-package-full/pom.xml b/packages/apex-pdp-package-full/pom.xml index de2ccf773..078088bad 100644 --- a/packages/apex-pdp-package-full/pom.xml +++ b/packages/apex-pdp-package-full/pom.xml @@ -40,7 +40,11 @@ services-engine ${project.version} - + + org.onap.policy.apex-pdp.services + services-onappf + ${project.version} + org.onap.policy.apex-pdp.client @@ -278,6 +282,15 @@ + + org.onap.policy.apex-pdp.services + services-onappf + ${project.version} + jar + false + ${project.build.directory}/etc/onappf + config/* + org.onap.policy.apex-pdp.auth cli-editor diff --git a/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.bat b/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.bat index 848498b1e..9798fa545 100644 --- a/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.bat +++ b/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.bat @@ -82,6 +82,7 @@ set APEX_APP_MAP[eng-deployment]=java -Dlogback.configurationFile=%APEX_HOME%\et set APEX_APP_MAP[eng-monitoring]=java -Dlogback.configurationFile=%APEX_HOME%\etc\logback.xml -jar %APEX_HOME%\lib\applications\client-monitoring-%_VERSION%-monitoring.jar set APEX_APP_MAP[full-client]=java -Dlogback.configurationFile=%APEX_HOME%\etc\logback.xml -jar %APEX_HOME%\lib\applications\client-full-%_VERSION%-full.jar set APEX_APP_MAP[event-generator]=java -Dlogback.configurationFile=%APEX_HOME%\etc\logback.xml -cp %CLASSPATH% %_CONFIG% org.onap.policy.apex.testsuites.performance.benchmark.eventgenerator.EventGenerator +set APEX_APP_MAP[onappf]=java -Dlogback.configurationFile=%APEX_HOME%\etc\logback.xml -cp %CLASSPATH% %_CONFIG% org.onap.policy.apex.services.onappf.ApexStarterMain :: array of applications with name=description :: declare -A APEX_APP_DESCR_MAP @@ -96,6 +97,7 @@ set APEX_APP_DESCR_MAP[eng-deployment]=starts the APEX deployment client in a si set APEX_APP_DESCR_MAP[eng-monitoring]=starts the APEX engine monitoring client in a simple webserver set APEX_APP_DESCR_MAP[full-client]=starts the full APEX client (rest editor, deployment, monitoring) in a simple webserver set APEX_APP_DESCR_MAP["event-generator"]=starts the event generator in a simple webserver for performance testing +set APEX_APP_DESCR_MAP[onappf]=starts the ApexStarter which handles the Apex Engine based on instructions from PAP :: no command line means help, -h means help if "%1" == "" goto Help diff --git a/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.sh b/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.sh index c5569baaa..52e1f3df9 100755 --- a/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.sh +++ b/packages/apex-pdp-package-full/src/main/package/scripts/apexApps.sh @@ -91,6 +91,7 @@ APEX_APP_MAP["eng-deployment"]="java -Dlogback.configurationFile=$APEX_HOME/etc/ APEX_APP_MAP["eng-monitoring"]="java -Dlogback.configurationFile=$APEX_HOME/etc/logback.xml -jar $APEX_HOME/lib/applications/client-monitoring-$_version-monitoring.jar" APEX_APP_MAP["full-client"]="java -Dlogback.configurationFile=$APEX_HOME/etc/logback.xml -jar $APEX_HOME/lib/applications/client-full-$_version-full.jar" APEX_APP_MAP["event-gen"]="java -Dlogback.configurationFile=$APEX_HOME/etc/logback.xml -cp ${CLASSPATH} $_config org.onap.policy.apex.testsuites.performance.benchmark.eventgenerator.EventGenerator" +APEX_APP_MAP["onappf"]="java -Dlogback.configurationFile=$APEX_HOME/etc/logback.xml -cp ${CLASSPATH} $_config org.onap.policy.apex.services.onappf.ApexStarterMain" ## array of applications with name=description declare -A APEX_APP_DESCR_MAP @@ -105,6 +106,7 @@ APEX_APP_DESCR_MAP["eng-deployment"]="starts the APEX deployment client in a sim APEX_APP_DESCR_MAP["eng-monitoring"]="starts the APEX engine monitoring client in a simple webserver" APEX_APP_DESCR_MAP["full-client"]="starts the full APEX client (rest editor, deployment, monitoring) in a simple webserver" APEX_APP_DESCR_MAP["event-generator"]="starts the event generator in a simple webserver for performance testing" +APEX_APP_DESCR_MAP["onappf"]="starts the ApexStarter which handles the Apex Engine based on instructions from PAP" ## ## Help screen and exit condition (i.e. too few arguments) diff --git a/packages/apex-pdp-package-full/src/main/package/scripts/apexOnapPf.bat b/packages/apex-pdp-package-full/src/main/package/scripts/apexOnapPf.bat new file mode 100644 index 000000000..45531233d --- /dev/null +++ b/packages/apex-pdp-package-full/src/main/package/scripts/apexOnapPf.bat @@ -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========================================================= + +:: +:: Script to run the onappf PDP-A, calls apexApps.bat +:: +:: @package org.onap.policy.apex +:: @author Ajith Sreekumar +:: @version v1.0.0 + +:: +:: DO NOT CHANGE CODE BELOW, unless you know what you are doing +:: + +@echo off +setlocal enableDelayedExpansion + + +if defined APEX_HOME ( + if exist "%APEX_HOME%\" ( + set _dummy=dir + ) else ( + echo[ + echo Apex directory 'APEX_HOME' not a directory + echo Please set environment for 'APEX_HOME' + echo[ + exit /b + ) +) else ( + echo[ + echo Apex directory 'APEX_HOME' not set + echo Please set environment for 'APEX_HOME' + echo[ + exit /b +) + +%APEX_HOME%\bin\apexApps.bat onappf %* diff --git a/packages/apex-pdp-package-full/src/main/package/scripts/apexOnapPf.sh b/packages/apex-pdp-package-full/src/main/package/scripts/apexOnapPf.sh new file mode 100644 index 000000000..3eaa25937 --- /dev/null +++ b/packages/apex-pdp-package-full/src/main/package/scripts/apexOnapPf.sh @@ -0,0 +1,67 @@ +#!/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 run onappf PDP-A, calls apexApps.sh +## +## @package org.onap.policy.apex +## @author Ajith Sreekumar +## @version v1.0.0 + + +if [ -z $APEX_USER ] +then + APEX_USER="apexuser" +fi + +id $APEX_USER > /dev/null 2>& 1 +if [ "$?" -ne "0" ] +then + echo 'cannot run apex, user "'$APEX_USER'" does not exit' + exit +fi + +if [ $(whoami) != "$APEX_USER" ] +then + echo 'Apex must be run as user "'$APEX_USER'"' + exit +fi + +if [ -z $APEX_HOME ] +then + APEX_HOME="/opt/app/policy/apex-pdp" +fi + +if [ ! -d $APEX_HOME ] +then + echo + echo 'Apex directory "'$APEX_HOME'" not set or not a directory' + echo "Please set environment for 'APEX_HOME'" + exit +fi + +if [ $(whoami) == "$APEX_USER" ] +then + $APEX_HOME/bin/apexApps.sh onappf $* +else + su $APEX_USER -c "$APEX_HOME/bin/apexApps.sh onappf $*" +fi diff --git a/services/services-onappf/pom.xml b/services/services-onappf/pom.xml index ef23ae76f..81df89483 100644 --- a/services/services-onappf/pom.xml +++ b/services/services-onappf/pom.xml @@ -33,131 +33,11 @@ This module handles the registration/deregistration of apex-pdp to ONAP Policy Framework. - - junit - junit - test - org.onap.policy.apex-pdp.services services-engine ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-context.plugins-context-distribution - plugins-context-distribution-hazelcast - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-context.plugins-context-distribution - plugins-context-distribution-infinispan - ${project.version} - - - - - org.onap.policy.apex-pdp.plugins.plugins-context.plugins-context-locking - plugins-context-locking-hazelcast - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-context.plugins-context-locking - plugins-context-locking-curator - ${project.version} - - - - - org.onap.policy.apex-pdp.plugins.plugins-context.plugins-context-schema - plugins-context-schema-avro - ${project.version} - - - - - org.onap.policy.apex-pdp.plugins.plugins-executor - plugins-executor-java - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-executor - plugins-executor-javascript - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-executor - plugins-executor-jruby - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-executor - plugins-executor-jython - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-executor - plugins-executor-mvel - ${project.version} - - - - - org.onap.policy.apex-pdp.plugins.plugins-persistence.plugins-persistence-jpa - plugins-persistence-jpa-eclipselink - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-persistence.plugins-persistence-jpa - plugins-persistence-jpa-hibernate - ${project.version} - - - - - org.onap.policy.apex-pdp.plugins.plugins-event.plugins-event-carrier - plugins-event-carrier-kafka - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-event.plugins-event-carrier - plugins-event-carrier-websocket - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-event.plugins-event-carrier - plugins-event-carrier-jms - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-event.plugins-event-carrier - plugins-event-carrier-restclient - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-event.plugins-event-carrier - plugins-event-carrier-restserver - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-event.plugins-event-carrier - plugins-event-carrier-restrequestor - ${project.version} - - - - - org.onap.policy.apex-pdp.plugins.plugins-event.plugins-event-protocol - plugins-event-protocol-xml - ${project.version} - - - org.onap.policy.apex-pdp.plugins.plugins-event.plugins-event-protocol - plugins-event-protocol-jms - ${project.version} - - - org.onap.policy.common policy-endpoints @@ -182,16 +62,22 @@ javax.ws.rs javax.ws.rs-api + + org.glassfish.hk2 + hk2-api + + + org.glassfish.hk2.external + javax.inject + ${version.policy.common} - org.glassfish.jersey.inject jersey-hk2 ${version.jersey} - org.onap.policy.common utils-test @@ -208,6 +94,8 @@ ${version.policy.models} + + org.assertj assertj-core @@ -218,5 +106,10 @@ powermock-api-mockito test + + junit + junit + test + diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterActivator.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterActivator.java new file mode 100644 index 000000000..0da554d75 --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterActivator.java @@ -0,0 +1,203 @@ +/*- + * ============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.apex.services.onappf; + +import java.util.List; +import java.util.Properties; + +import lombok.Getter; +import lombok.Setter; + +import org.onap.policy.apex.services.onappf.comm.PdpStateChangeListener; +import org.onap.policy.apex.services.onappf.comm.PdpStatusPublisher; +import org.onap.policy.apex.services.onappf.comm.PdpUpdateListener; +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +import org.onap.policy.apex.services.onappf.exception.ApexStarterRunTimeException; +import org.onap.policy.apex.services.onappf.handler.PdpMessageHandler; +import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class activates the ApexStarter as a complete service together with all its handlers. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class ApexStarterActivator { + + private static final Logger LOGGER = LoggerFactory.getLogger(ApexStarterActivator.class); + private final ApexStarterParameterGroup apexStarterParameterGroup; + private List topicSinks;// topics to which apex-pdp sends pdp status + private List topicSources; // topics to which apex-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; + + public ApexStarterActivator(final ApexStarterParameterGroup apexStarterParameterGroup, + final Properties topicProperties) { + + topicSinks = TopicEndpoint.manager.addTopicSinks(topicProperties); + topicSources = TopicEndpoint.manager.addTopicSources(topicProperties); + + // TODO: instanceId currently set as a random string, could be fetched from actual deployment + final int random = (int) (Math.random() * 100); + final String instanceId = "apex_" + random; + LOGGER.debug("ApexStarterActivator initializing with instance id:" + instanceId); + try { + this.apexStarterParameterGroup = apexStarterParameterGroup; + this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES); + } catch (final RuntimeException e) { + throw new ApexStarterRunTimeException(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(ApexStarterConstants.REG_PDP_STATUS_OBJECT, + new PdpMessageHandler().createPdpStatusFromParameters(instanceId, + apexStarterParameterGroup.getPdpStatusParameters())), + () -> Registry.unregister(ApexStarterConstants.REG_PDP_STATUS_OBJECT)) + .addAction("topic sinks", + () -> Registry.register(ApexStarterConstants.REG_APEX_PDP_TOPIC_SINKS, topicSinks), + () -> Registry.unregister(ApexStarterConstants.REG_APEX_PDP_TOPIC_SINKS)) + .addAction("Pdp Status publisher", + () -> Registry.register(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, + new PdpStatusPublisher(topicSinks, + apexStarterParameterGroup.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(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class); + pdpStatusPublisher.terminate(); + Registry.unregister(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER); + } + + /** + * Initialize ApexStarter service. + * + * @throws ApexStarterException on errors in initializing the service + */ + public void initialize() throws ApexStarterException { + if (isAlive()) { + throw new IllegalStateException("activator already initialized"); + } + + try { + LOGGER.debug("ApexStarter starting as a service . . ."); + manager.start(); + LOGGER.debug("ApexStarter started as a service"); + } catch (final ServiceManagerException exp) { + LOGGER.error("ApexStarter service startup failed"); + throw new ApexStarterException(exp.getMessage(), exp); + } + } + + /** + * Terminate ApexStarter. + * + * @throws ApexStarterException on errors in terminating the service + */ + public void terminate() throws ApexStarterException { + if (!isAlive()) { + throw new IllegalStateException("activator is not running"); + } + try { + final PdpStatusPublisher pdpStatusPublisher = + Registry.get(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class); + // send a final heartbeat with terminated status + pdpStatusPublisher.send(new PdpMessageHandler().getTerminatedPdpStatus()); + manager.stop(); + Registry.unregister(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR); + } catch (final ServiceManagerException exp) { + LOGGER.error("ApexStarter termination failed"); + throw new ApexStarterException(exp.getMessage(), exp); + } + } + + /** + * Get the parameters used by the activator. + * + * @return the parameters of the activator + */ + public ApexStarterParameterGroup getParameterGroup() { + return apexStarterParameterGroup; + } + + /** + * 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/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterCommandLineArguments.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterCommandLineArguments.java new file mode 100644 index 000000000..152182b52 --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterCommandLineArguments.java @@ -0,0 +1,299 @@ +/*- + * ============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.apex.services.onappf; + +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.apex.services.onappf.exception.ApexStarterException; +import org.onap.policy.apex.services.onappf.exception.ApexStarterRunTimeException; +import org.onap.policy.common.utils.resources.ResourceUtils; + +/** + * This class reads and handles command line parameters for the apex starter. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class ApexStarterCommandLineArguments { + + 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 ApexStarterCommandLineArguments() { + //@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 apex starter") + .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 apex starter 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 apex starter 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 ApexStarterCommandLineArguments(final String[] args) { + // Set up the options with the default constructor + this(); + + // Parse the arguments + try { + parse(args); + } catch (final ApexStarterException e) { + throw new ApexStarterRunTimeException("parse error on apex starter 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 ApexStarterException on command argument errors + */ + public String parse(final String[] args) throws ApexStarterException { + // Clear all our arguments + setConfigurationFilePath(null); + setPropertyFilePath(null); + + CommandLine commandLine = null; + try { + commandLine = new DefaultParser().parse(options, args); + } catch (final ParseException e) { + throw new ApexStarterException("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 ApexStarterException("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 ApexStarterException on command argument validation errors + */ + public void validate() throws ApexStarterException { + validateReadableFile("apex starter configuration", configurationFilePath); + validateReadableFile("apex starter properties", propertyFilePath); + } + + /** + * Print version information for apex starter. + * + * @return the version string + */ + public String version() { + return ResourceUtils.getResourceAsString("src/main/resources/version.txt"); + } + + /** + * Print help information for apex starter. + * + * @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 ApexStarterException on the file name passed as a parameter + */ + private void validateReadableFile(final String fileTag, final String fileName) throws ApexStarterException { + if (fileName == null || fileName.length() == 0) { + throw new ApexStarterException(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 ApexStarterException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); + } + + final File theFile = new File(fileUrl.getPath()); + if (!theFile.exists()) { + throw new ApexStarterException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); + } + if (!theFile.isFile()) { + throw new ApexStarterException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file"); + } + if (!theFile.canRead()) { + throw new ApexStarterException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is ureadable"); + } + } + +} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterConstants.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterConstants.java new file mode 100644 index 000000000..c6dbf5fe3 --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterConstants.java @@ -0,0 +1,34 @@ +/*- + * ============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.apex.services.onappf; + +/** + * Names of various items contained in the Registry. + */ +public class ApexStarterConstants { + // Registry keys + public static final String REG_APEX_STARTER_ACTIVATOR = "object:activator/apex_starter"; + public static final String REG_PDP_STATUS_OBJECT = "object:pdp/status"; + public static final String REG_APEX_TOSCA_POLICY_LIST = "object:apex/tosca/policy/list"; + public static final String REG_PDP_STATUS_PUBLISHER = "object:pdp/status/publisher"; + public static final String REG_APEX_PDP_TOPIC_SINKS = "object:apex/pdp/topic/sinks"; + public static final String REG_APEX_ENGINE_HANDLER = "object:engine/apex/handler"; +} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterMain.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterMain.java new file mode 100644 index 000000000..22611c51b --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/ApexStarterMain.java @@ -0,0 +1,165 @@ +/*- + * ============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.apex.services.onappf; + +import java.io.FileInputStream; +import java.util.Arrays; +import java.util.Properties; + +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup; +import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterHandler; +import org.onap.policy.common.utils.services.Registry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class initiates Apex as a service based on instructions from PAP. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class ApexStarterMain { + + private static final Logger LOGGER = LoggerFactory.getLogger(ApexStarterMain.class); + + private ApexStarterActivator activator; + private ApexStarterParameterGroup parameterGroup; + + /** + * Instantiates the ApexStarter. + * + * @param args the command line arguments + */ + ApexStarterMain(final String[] args) { + LOGGER.info("In ApexStarter with parameters " + Arrays.toString(args)); + + // Check the arguments + final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); + 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 ApexStarterException e) { + LOGGER.error("start of ApexStarter failed", e); + return; + } + + // Read the parameters + try { + parameterGroup = new ApexStarterParameterHandler().getParameters(arguments); + } catch (final Exception e) { + LOGGER.error("start of ApexStarter failed", 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("start of ApexStarter failed", e); + return; + } + + // create the activator + activator = new ApexStarterActivator(parameterGroup, topicProperties); + Registry.register(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, activator); + // Start the activator + try { + activator.initialize(); + } catch (final ApexStarterException e) { + LOGGER.error("start of ApexStarter failed, used parameters are {}", Arrays.toString(args), e); + Registry.unregister(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR); + return; + } + + // Add a shutdown hook to shut everything down in an orderly manner + Runtime.getRuntime().addShutdownHook(new ApexStarterShutdownHookClass()); + + LOGGER.info("Started ApexStarter service"); + } + + /** + * Get the parameters specified in JSON. + * + * @return the parameters + */ + public ApexStarterParameterGroup getParameters() { + return parameterGroup; + } + + + /** + * Shut down Execution. + * + * @throws ApexStarterException on shutdown errors + */ + public void shutdown() throws ApexStarterException { + // clear the parameterGroup variable + parameterGroup = null; + + // clear the apex starter activator + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } + + /** + * The Class ApexStarterShutdownHookClass terminates the Apex starter for the Apex service when its run method is + * called. + */ + private class ApexStarterShutdownHookClass extends Thread { + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + try { + // Shutdown the apex starter service and wait for everything to stop + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } catch (final ApexStarterException e) { + LOGGER.warn("error occured during shut down of the apex starter service", e); + } + } + } + + /** + * The main method. + * + * @param args the arguments + * + */ + public static void main(final String[] args) { + new ApexStarterMain(args); + } +} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/comm/PdpStateChangeListener.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/comm/PdpStateChangeListener.java new file mode 100644 index 000000000..404749051 --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/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.apex.services.onappf.comm; + +import org.onap.policy.apex.services.onappf.handler.PdpStateChangeMessageHandler; +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.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/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/comm/PdpStatusPublisher.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/comm/PdpStatusPublisher.java new file mode 100644 index 000000000..211fe1316 --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/comm/PdpStatusPublisher.java @@ -0,0 +1,92 @@ +/*- + * ============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.apex.services.onappf.comm; + +import java.util.List; +import java.util.Timer; +import java.util.TimerTask; + +import org.onap.policy.apex.services.onappf.handler.PdpMessageHandler; +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.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 pdpStatus + * @param topicSinks + * @param apexStarterParameterGroup + */ + 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 + */ + public long getInterval() { + return interval; + } + + /** + * Method to send pdp status message to pap on demand. + */ + public void send(final PdpStatus pdpStatus) { + topicSinkClient.send(pdpStatus); + LOGGER.debug("Sent pdp status message to PAP - {}", pdpStatus); + } +} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/comm/PdpUpdateListener.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/comm/PdpUpdateListener.java new file mode 100644 index 000000000..5633d60fb --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/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.apex.services.onappf.comm; + +import org.onap.policy.apex.services.onappf.handler.PdpUpdateMessageHandler; +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.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/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/exception/ApexStarterException.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/exception/ApexStarterException.java new file mode 100644 index 000000000..461d758c9 --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/exception/ApexStarterException.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.apex.services.onappf.exception; + +/** + * This exception will be called if an error occurs in apex starter. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class ApexStarterException extends Exception { + private static final long serialVersionUID = -510646141043975917L; + + /** + * Instantiates a new apex starter exception with a message. + * + * @param message the message + */ + public ApexStarterException(final String message) { + super(message); + } + + /** + * Instantiates a new apex starter exception caused by an exception. + * + * @param exception the exception that caused this exception to be thrown + */ + public ApexStarterException(final Exception exception) { + super(exception); + } + + /** + * Instantiates a new apex starter 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 ApexStarterException(final String message, final Exception exception) { + super(message, exception); + } + +} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/exception/ApexStarterRunTimeException.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/exception/ApexStarterRunTimeException.java new file mode 100644 index 000000000..a1c970a56 --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/exception/ApexStarterRunTimeException.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.apex.services.onappf.exception; + +/** + * This runtime exception will be called if a runtime error occurs when using apex starter. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class ApexStarterRunTimeException extends RuntimeException { + private static final long serialVersionUID = -6024353312002272098L; + + /** + * Instantiates a new apex starter runtime exception with a message. + * + * @param message the message + */ + public ApexStarterRunTimeException(final String message) { + super(message); + } + + /** + * Instantiates a new apex starter runtime exception caused by an exception. + * + * @param exception the exception that caused this exception to be thrown + */ + public ApexStarterRunTimeException(final Exception exception) { + super(exception); + } + + /** + * Instantiates a new apex starter 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 ApexStarterRunTimeException(final String message, final Exception exception) { + super(message, exception); + } +} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/ApexEngineHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/ApexEngineHandler.java new file mode 100644 index 000000000..83e1b77c6 --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/ApexEngineHandler.java @@ -0,0 +1,110 @@ +/*- + * ============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.apex.services.onappf.handler; + +import com.google.gson.JsonObject; + +import java.io.IOException; +import java.io.StringReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.service.engine.main.ApexMain; +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class instantiates the Apex Engine based on instruction from PAP. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class ApexEngineHandler { + private static final Logger LOGGER = LoggerFactory.getLogger(ApexEngineHandler.class); + + private ApexMain apexMain; + + /** + * Constructs the object. Extracts the apex config and model files and instantiates the apex engine. + * + * @param properties + * @return ApexEngineHandler + * @throws ApexStarterException + */ + + public ApexEngineHandler(final String properties) throws ApexStarterException { + final StandardCoder standardCoder = new StandardCoder(); + JsonObject body; + try { + body = standardCoder.decode(new StringReader(properties), JsonObject.class); + } catch (final CoderException e) { + throw new ApexStarterException(e); + } + final JsonObject engineServiceParameters = body.get("engineServiceParameters").getAsJsonObject(); + final String policyModel = engineServiceParameters.get("policy_type_impl").toString(); + engineServiceParameters.remove("policy_type_impl"); + final String apexConfig = body.toString(); + + final String modelFilePath = createFile(policyModel, "modelFile"); + + final String apexConfigFilePath = createFile(apexConfig, "apexConfigFile"); + final String[] apexArgs = { "-c", apexConfigFilePath, "-m", modelFilePath }; + LOGGER.debug("Starting apex engine."); + apexMain = new ApexMain(apexArgs); + } + + /** + * Method to create the policy model file + * + * @param policyModel + * @param modelFilePath + * @throws ApexStarterException + */ + private String createFile(final String fileContent, final String fileName) throws ApexStarterException { + try { + final Path path = Files.createTempFile(fileName, ".json"); + Files.write(path, fileContent.getBytes(StandardCharsets.UTF_8)); + return path.toAbsolutePath().toString(); + } catch (final IOException e) { + final String errorMessage = "error creating from the properties received in PdpUpdate."; + LOGGER.error(errorMessage, e); + throw new ApexStarterException(errorMessage, e); + } + } + + public boolean isApexEngineRunning() { + return null != apexMain; + } + + public void shutdown() throws ApexStarterException { + try { + LOGGER.debug("Shutting down apex engine."); + apexMain.shutdown(); + apexMain = null; + } catch (final ApexException e) { + throw new ApexStarterException(e); + } + } +} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpMessageHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpMessageHandler.java new file mode 100644 index 000000000..e3f0c04a1 --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpMessageHandler.java @@ -0,0 +1,152 @@ +/*- + * ============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.apex.services.onappf.handler; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.policy.apex.services.onappf.ApexStarterConstants; +import org.onap.policy.apex.services.onappf.parameters.PdpStatusParameters; +import org.onap.policy.apex.services.onappf.parameters.ToscaPolicyTypeIdentifierParameters; +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.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 apex 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 + * @return 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 apex-pdp to pap. + * + * @return PdpStatus the pdp status message + */ + public PdpStatus createPdpStatusFromContext() { + final PdpStatus pdpStatusContext = Registry.get(ApexStarterConstants.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 apex started is shutting down. + * + * @param policies list of ToscaPolicy + * + * @return PdpStatus + */ + public PdpStatus getTerminatedPdpStatus() { + final PdpStatus pdpStatusInContext = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); + pdpStatusInContext.setState(PdpState.TERMINATED); + pdpStatusInContext.setDescription("Apex pdp 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/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpStateChangeMessageHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpStateChangeMessageHandler.java new file mode 100644 index 000000000..3a186aed6 --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpStateChangeMessageHandler.java @@ -0,0 +1,138 @@ +/*- + * ============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.apex.services.onappf.handler; + +import java.util.List; + +import org.onap.policy.apex.services.onappf.ApexStarterConstants; +import org.onap.policy.apex.services.onappf.comm.PdpStatusPublisher; +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +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.tosca.authorative.concepts.ToscaPolicy; + +/** + * This class supports the handling of pdp state change messages. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpStateChangeMessageHandler { + + /** + * 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(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); + final PdpStatusPublisher pdpStatusPublisher = Registry.get(ApexStarterConstants.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 + * @param pdpStatusContext + * @param pdpMessageHandler + * @return pdpResponseDetails + */ + 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(ApexStarterConstants.REG_APEX_TOSCA_POLICY_LIST); + if (policies.isEmpty()) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "No policies found. Apex engine not running."); + } else { + try { + // assumed that the apex policies list contains only one entry. + final ApexEngineHandler apexEngineHandler = + new ApexEngineHandler((String) policies.get(0).getProperties().get("content")); + Registry.registerOrReplace(ApexStarterConstants.REG_APEX_ENGINE_HANDLER, apexEngineHandler); + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Apex engine started. State changed to active."); + pdpStatusContext.setState(PdpState.ACTIVE); + } catch (final ApexStarterException e) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.FAIL, "Apex engine service running failed. " + e.getMessage()); + } + } + } + return pdpResponseDetails; + } + + /** + * Method to handle when the new state from pap is passive. + * + * @param pdpStateChangeMsg + * @param pdpStatusContext + * @param pdpMessageHandler + * @return pdpResponseDetails + */ + 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 { + final ApexEngineHandler apexEngineHandler = Registry.get(ApexStarterConstants.REG_APEX_ENGINE_HANDLER); + try { + apexEngineHandler.shutdown(); + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Apex pdp state changed from Active to Passive."); + pdpStatusContext.setState(PdpState.PASSIVE); + } catch (final Exception e) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), + PdpResponseStatus.FAIL, + "Stopping apex engine failed. State cannot be changed to Passive." + e.getMessage()); + } + } + return pdpResponseDetails; + } +} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpUpdateMessageHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpUpdateMessageHandler.java new file mode 100644 index 000000000..3ad5477cd --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/handler/PdpUpdateMessageHandler.java @@ -0,0 +1,163 @@ +/*- + * ============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.apex.services.onappf.handler; + +import java.util.List; + +import org.onap.policy.apex.services.onappf.ApexStarterConstants; +import org.onap.policy.apex.services.onappf.comm.PdpStatusPublisher; +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +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; + +/** + * This class supports the handling of pdp update messages. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class PdpUpdateMessageHandler { + + /** + * 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(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); + PdpResponseDetails pdpResponseDetails = null; + if (pdpUpdateMsg.appliesTo(pdpStatusContext.getName(), pdpStatusContext.getPdpGroup(), + pdpStatusContext.getPdpSubgroup())) { + final PdpStatusPublisher pdpStatusPublisher = Registry.get(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER); + if (checkIfAlreadyHandled(pdpUpdateMsg, pdpStatusContext, pdpStatusPublisher.getInterval())) { + 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)) { + pdpResponseDetails = + startOrStopApexEngineBasedOnPolicies(pdpUpdateMsg, pdpMessageHandler, pdpStatusContext); + } + Registry.registerOrReplace(ApexStarterConstants.REG_APEX_TOSCA_POLICY_LIST, pdpUpdateMsg.getPolicies()); + if (null == pdpResponseDetails) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Pdp update successful."); + } + } + final PdpStatusPublisher pdpStatusPublisherTemp = + Registry.get(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER); + final PdpStatus pdpStatus = pdpMessageHandler.createPdpStatusFromContext(); + pdpStatus.setResponse(pdpResponseDetails); + pdpStatus.setDescription("Pdp status response message for PdpUpdate"); + pdpStatusPublisherTemp.send(pdpStatus); + } + } + + /** + * Method to start or stop apex engine based on the list of policies received from pap. When current state is + * active, if PAP sends PdpUpdate with empty policies list, stop apex engine, or, if there is a change in policies, + * stop the current running policies and the deploy the new ones. + * + * @param pdpUpdateMsg + * @param pdpMessageHandler + * @param pdpStatusContext + * @return pdpResponseDetails + */ + private PdpResponseDetails startOrStopApexEngineBasedOnPolicies(final PdpUpdate pdpUpdateMsg, + final PdpMessageHandler pdpMessageHandler, final PdpStatus pdpStatusContext) { + PdpResponseDetails pdpResponseDetails = null; + if (pdpUpdateMsg.getPolicies().isEmpty()) { + final ApexEngineHandler apexEngineHandler = Registry.get(ApexStarterConstants.REG_APEX_ENGINE_HANDLER); + if (apexEngineHandler.isApexEngineRunning()) { + try { + apexEngineHandler.shutdown(); + } catch (final ApexStarterException e) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + PdpResponseStatus.FAIL, "Pdp update failed as the policies couldn't be undeployed."); + } + } + } else { + try { + ApexEngineHandler apexEngineHandler = Registry.get(ApexStarterConstants.REG_APEX_ENGINE_HANDLER); + if (apexEngineHandler.isApexEngineRunning()) { + apexEngineHandler.shutdown(); + } + apexEngineHandler = new ApexEngineHandler( + (String) pdpUpdateMsg.getPolicies().get(0).getProperties().get("content")); + Registry.registerOrReplace(ApexStarterConstants.REG_APEX_ENGINE_HANDLER, apexEngineHandler); + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + PdpResponseStatus.SUCCESS, "Apex engine started and policies are running."); + } catch (final ApexStarterException e) { + pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), + PdpResponseStatus.FAIL, "Apex engine service running failed. " + e.getMessage()); + } + } + return pdpResponseDetails; + } + + /** + * Method checks of 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 + * @param interval the current interval in which the pdp status publisher is sending the heartbeats + * @return boolean flag which tells if the information is same or not + */ + private boolean checkIfAlreadyHandled(final PdpUpdate pdpUpdateMsg, final PdpStatus pdpStatusContext, + final long interval) { + 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()) + && (null == pdpUpdateMsg.getPdpHeartbeatIntervalMs() + || (null != pdpUpdateMsg.getPdpHeartbeatIntervalMs() + && pdpUpdateMsg.getPdpHeartbeatIntervalMs() > 0 + && interval == pdpUpdateMsg.getPdpHeartbeatIntervalMs())); + } + + /** + * 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(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER); + pdpStatusPublisher.terminate(); + final List topicSinks = Registry.get(ApexStarterConstants.REG_APEX_PDP_TOPIC_SINKS); + Registry.registerOrReplace(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, + new PdpStatusPublisher(topicSinks, interval)); + } +} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/ApexStarterParameterGroup.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/ApexStarterParameterGroup.java new file mode 100644 index 000000000..523e37337 --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/ApexStarterParameterGroup.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.services.onappf.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 apex starter component. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +@NotNull +@NotBlank +@Getter +public class ApexStarterParameterGroup extends ParameterGroupImpl { + + private PdpStatusParameters pdpStatusParameters; + + /** + * Create the apex starter parameter group. + * + * @param name the parameter group name + */ + public ApexStarterParameterGroup(final String name) { + super(name); + } +} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/ApexStarterParameterHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/ApexStarterParameterHandler.java new file mode 100644 index 000000000..ed7c00f10 --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/ApexStarterParameterHandler.java @@ -0,0 +1,88 @@ +/*- + * ============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.apex.services.onappf.parameters; + +import java.io.File; + +import org.onap.policy.apex.services.onappf.ApexStarterCommandLineArguments; +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class handles reading, parsing and validating of apex starter parameters from JSON files. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class ApexStarterParameterHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(ApexStarterParameterHandler.class); + private static final Coder CODER = new StandardCoder(); + + /** + * Read the parameters from the parameter file. + * + * @param arguments the arguments passed to apex starter + * @return the parameters read from the configuration file + * @throws ApexStarterException on parameter exceptions + */ + public ApexStarterParameterGroup getParameters(final ApexStarterCommandLineArguments arguments) + throws ApexStarterException { + ApexStarterParameterGroup apexStarterParameterGroup = null; + + // Read the parameters + try { + // Read the parameters from JSON + final File file = new File(arguments.getFullConfigurationFilePath()); + apexStarterParameterGroup = CODER.decode(file, ApexStarterParameterGroup.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 ApexStarterException(errorMessage, e); + } + + // The JSON processing returns null if there is an empty file + if (apexStarterParameterGroup == null) { + final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\""; + LOGGER.error(errorMessage); + throw new ApexStarterException(errorMessage); + } + + // validate the parameters + final GroupValidationResult validationResult = apexStarterParameterGroup.validate(); + if (!validationResult.isValid()) { + String returnMessage = + "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n"; + returnMessage += validationResult.getResult(); + + LOGGER.error(returnMessage); + throw new ApexStarterException(returnMessage); + } + + return apexStarterParameterGroup; + } + +} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/PdpStatusParameters.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/PdpStatusParameters.java new file mode 100644 index 000000000..962a98e4c --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/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.apex.services.onappf.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/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/ToscaPolicyTypeIdentifierParameters.java b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/parameters/ToscaPolicyTypeIdentifierParameters.java new file mode 100644 index 000000000..a08b9347c --- /dev/null +++ b/services/services-onappf/src/main/java/org/onap/policy/apex/services/onappf/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.apex.services.onappf.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/services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterActivator.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterActivator.java deleted file mode 100644 index b33d792a0..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterActivator.java +++ /dev/null @@ -1,201 +0,0 @@ -/*- - * ============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.apex.starter; - -import java.util.List; -import java.util.Properties; - -import lombok.Getter; -import lombok.Setter; - -import org.onap.policy.apex.starter.comm.PdpStateChangeListener; -import org.onap.policy.apex.starter.comm.PdpStatusPublisher; -import org.onap.policy.apex.starter.comm.PdpUpdateListener; -import org.onap.policy.apex.starter.exception.ApexStarterException; -import org.onap.policy.apex.starter.exception.ApexStarterRunTimeException; -import org.onap.policy.apex.starter.handler.PdpMessageHandler; -import org.onap.policy.apex.starter.parameters.ApexStarterParameterGroup; -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.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class activates the ApexStarter as a complete service together with all its handlers. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class ApexStarterActivator { - - private static final Logger LOGGER = LoggerFactory.getLogger(ApexStarterActivator.class); - private final ApexStarterParameterGroup apexStarterParameterGroup; - private List topicSinks;// topics to which apex-pdp sends pdp status - private List topicSources; // topics to which apex-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; - - public ApexStarterActivator(final ApexStarterParameterGroup apexStarterParameterGroup, - final Properties topicProperties) { - - topicSinks = TopicEndpoint.manager.addTopicSinks(topicProperties); - topicSources = TopicEndpoint.manager.addTopicSources(topicProperties); - - // TODO: instanceId currently set as a random string, could be fetched from actual deployment - final int random = (int) (Math.random() * 100); - final String instanceId = "apex_" + random; - LOGGER.debug("ApexStarterActivator initializing with instance id:" + instanceId); - try { - this.apexStarterParameterGroup = apexStarterParameterGroup; - this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES); - } catch (final RuntimeException e) { - throw new ApexStarterRunTimeException(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(ApexStarterConstants.REG_PDP_STATUS_OBJECT, - new PdpMessageHandler().createPdpStatusFromParameters(instanceId, - apexStarterParameterGroup.getPdpStatusParameters())), - () -> Registry.unregister(ApexStarterConstants.REG_PDP_STATUS_OBJECT)) - .addAction("topic sinks", - () -> Registry.register(ApexStarterConstants.REG_APEX_PDP_TOPIC_SINKS, topicSinks), - () -> Registry.unregister(ApexStarterConstants.REG_APEX_PDP_TOPIC_SINKS)) - .addAction("Pdp Status publisher", - () -> Registry.register(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, - new PdpStatusPublisher(topicSinks, - apexStarterParameterGroup.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(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class); - // send a final heartbeat with terminated status - pdpStatusPublisher.send(new PdpMessageHandler().getTerminatedPdpStatus()); - pdpStatusPublisher.terminate(); - Registry.unregister(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER); - } - - /** - * Initialize ApexStarter service. - * - * @throws ApexStarterException on errors in initializing the service - */ - public void initialize() throws ApexStarterException { - if (isAlive()) { - throw new IllegalStateException("activator already initialized"); - } - - try { - LOGGER.debug("ApexStarter starting as a service . . ."); - manager.start(); - LOGGER.debug("ApexStarter started as a service"); - } catch (final ServiceManagerException exp) { - LOGGER.error("ApexStarter service startup failed"); - throw new ApexStarterException(exp.getMessage(), exp); - } - } - - /** - * Terminate ApexStarter. - * - * @throws ApexStarterException on errors in terminating the service - */ - public void terminate() throws ApexStarterException { - if (!isAlive()) { - throw new IllegalStateException("activator is not running"); - } - try { - manager.stop(); - Registry.unregister(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR); - } catch (final ServiceManagerException exp) { - LOGGER.error("ApexStarter termination failed"); - throw new ApexStarterException(exp.getMessage(), exp); - } - } - - /** - * Get the parameters used by the activator. - * - * @return the parameters of the activator - */ - public ApexStarterParameterGroup getParameterGroup() { - return apexStarterParameterGroup; - } - - /** - * 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/services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterCommandLineArguments.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterCommandLineArguments.java deleted file mode 100644 index f1d082fcb..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterCommandLineArguments.java +++ /dev/null @@ -1,299 +0,0 @@ -/*- - * ============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.apex.starter; - -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.apex.starter.exception.ApexStarterException; -import org.onap.policy.apex.starter.exception.ApexStarterRunTimeException; -import org.onap.policy.common.utils.resources.ResourceUtils; - -/** - * This class reads and handles command line parameters for the apex starter. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class ApexStarterCommandLineArguments { - - 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 ApexStarterCommandLineArguments() { - //@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 apex starter") - .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 apex starter 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 apex starter 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 ApexStarterCommandLineArguments(final String[] args) { - // Set up the options with the default constructor - this(); - - // Parse the arguments - try { - parse(args); - } catch (final ApexStarterException e) { - throw new ApexStarterRunTimeException("parse error on apex starter 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 ApexStarterException on command argument errors - */ - public String parse(final String[] args) throws ApexStarterException { - // Clear all our arguments - setConfigurationFilePath(null); - setPropertyFilePath(null); - - CommandLine commandLine = null; - try { - commandLine = new DefaultParser().parse(options, args); - } catch (final ParseException e) { - throw new ApexStarterException("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 ApexStarterException("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 ApexStarterException on command argument validation errors - */ - public void validate() throws ApexStarterException { - validateReadableFile("apex starter configuration", configurationFilePath); - validateReadableFile("apex starter properties", propertyFilePath); - } - - /** - * Print version information for apex starter. - * - * @return the version string - */ - public String version() { - return ResourceUtils.getResourceAsString("src/main/resources/version.txt"); - } - - /** - * Print help information for apex starter. - * - * @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 ApexStarterException on the file name passed as a parameter - */ - private void validateReadableFile(final String fileTag, final String fileName) throws ApexStarterException { - if (fileName == null || fileName.length() == 0) { - throw new ApexStarterException(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 ApexStarterException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); - } - - final File theFile = new File(fileUrl.getPath()); - if (!theFile.exists()) { - throw new ApexStarterException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); - } - if (!theFile.isFile()) { - throw new ApexStarterException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file"); - } - if (!theFile.canRead()) { - throw new ApexStarterException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is ureadable"); - } - } - -} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterConstants.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterConstants.java deleted file mode 100644 index 6173872e0..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterConstants.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============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.apex.starter; - -/** - * Names of various items contained in the Registry. - */ -public class ApexStarterConstants { - // Registry keys - public static final String REG_APEX_STARTER_ACTIVATOR = "object:activator/apex_starter"; - public static final String REG_PDP_STATUS_OBJECT = "object:pdp/status"; - public static final String REG_APEX_TOSCA_POLICY_LIST = "object:apex/tosca/policy/list"; - public static final String REG_PDP_STATUS_PUBLISHER = "object:pdp/status/publisher"; - public static final String REG_APEX_PDP_TOPIC_SINKS = "object:apex/pdp/topic/sinks"; - public static final String REG_APEX_ENGINE_HANDLER = "object:engine/apex/handler"; -} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterMain.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterMain.java deleted file mode 100644 index e4465ed92..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/ApexStarterMain.java +++ /dev/null @@ -1,165 +0,0 @@ -/*- - * ============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.apex.starter; - -import java.io.FileInputStream; -import java.util.Arrays; -import java.util.Properties; - -import org.onap.policy.apex.starter.exception.ApexStarterException; -import org.onap.policy.apex.starter.parameters.ApexStarterParameterGroup; -import org.onap.policy.apex.starter.parameters.ApexStarterParameterHandler; -import org.onap.policy.common.utils.services.Registry; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class initiates Apex as a service based on instructions from PAP. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class ApexStarterMain { - - private static final Logger LOGGER = LoggerFactory.getLogger(ApexStarterMain.class); - - private ApexStarterActivator activator; - private ApexStarterParameterGroup parameterGroup; - - /** - * Instantiates the ApexStarter. - * - * @param args the command line arguments - */ - ApexStarterMain(final String[] args) { - LOGGER.info("In ApexStarter with parameters " + Arrays.toString(args)); - - // Check the arguments - final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); - 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 ApexStarterException e) { - LOGGER.error("start of ApexStarter failed", e); - return; - } - - // Read the parameters - try { - parameterGroup = new ApexStarterParameterHandler().getParameters(arguments); - } catch (final Exception e) { - LOGGER.error("start of ApexStarter failed", 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("start of ApexStarter failed", e); - return; - } - - // create the activator - activator = new ApexStarterActivator(parameterGroup, topicProperties); - Registry.register(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, activator); - // Start the activator - try { - activator.initialize(); - } catch (final ApexStarterException e) { - LOGGER.error("start of ApexStarter failed, used parameters are {}", Arrays.toString(args), e); - Registry.unregister(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR); - return; - } - - // Add a shutdown hook to shut everything down in an orderly manner - Runtime.getRuntime().addShutdownHook(new ApexStarterShutdownHookClass()); - - LOGGER.info("Started ApexStarter service"); - } - - /** - * Get the parameters specified in JSON. - * - * @return the parameters - */ - public ApexStarterParameterGroup getParameters() { - return parameterGroup; - } - - - /** - * Shut down Execution. - * - * @throws ApexStarterException on shutdown errors - */ - public void shutdown() throws ApexStarterException { - // clear the parameterGroup variable - parameterGroup = null; - - // clear the apex starter activator - if (activator != null && activator.isAlive()) { - activator.terminate(); - } - } - - /** - * The Class ApexStarterShutdownHookClass terminates the Apex starter for the Apex service when its run method is - * called. - */ - private class ApexStarterShutdownHookClass extends Thread { - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - try { - // Shutdown the apex starter service and wait for everything to stop - if (activator != null && activator.isAlive()) { - activator.terminate(); - } - } catch (final ApexStarterException e) { - LOGGER.warn("error occured during shut down of the apex starter service", e); - } - } - } - - /** - * The main method. - * - * @param args the arguments - * - */ - public static void main(final String[] args) { - new ApexStarterMain(args); - } -} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/comm/PdpStateChangeListener.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/comm/PdpStateChangeListener.java deleted file mode 100644 index 0bd0d935f..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/comm/PdpStateChangeListener.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============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.apex.starter.comm; - -import org.onap.policy.apex.starter.handler.PdpStateChangeMessageHandler; -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.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/services/services-onappf/src/main/java/org/onap/policy/apex/starter/comm/PdpStatusPublisher.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/comm/PdpStatusPublisher.java deleted file mode 100644 index 69c9dd18d..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/comm/PdpStatusPublisher.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============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.apex.starter.comm; - -import java.util.List; -import java.util.Timer; -import java.util.TimerTask; - -import org.onap.policy.apex.starter.handler.PdpMessageHandler; -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.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 pdpStatus - * @param topicSinks - * @param apexStarterParameterGroup - */ - 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 - */ - public long getInterval() { - return interval; - } - - /** - * Method to send pdp status message to pap on demand. - */ - public void send(final PdpStatus pdpStatus) { - topicSinkClient.send(pdpStatus); - LOGGER.debug("Sent pdp status message to PAP - {}", pdpStatus); - } -} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/comm/PdpUpdateListener.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/comm/PdpUpdateListener.java deleted file mode 100644 index 46ce30e57..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/comm/PdpUpdateListener.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============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.apex.starter.comm; - -import org.onap.policy.apex.starter.handler.PdpUpdateMessageHandler; -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.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/services/services-onappf/src/main/java/org/onap/policy/apex/starter/engine/ApexEngineHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/engine/ApexEngineHandler.java deleted file mode 100644 index e58b0db76..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/engine/ApexEngineHandler.java +++ /dev/null @@ -1,110 +0,0 @@ -/*- - * ============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.apex.starter.engine; - -import com.google.gson.JsonObject; - -import java.io.IOException; -import java.io.StringReader; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; - -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.service.engine.main.ApexMain; -import org.onap.policy.apex.starter.exception.ApexStarterException; -import org.onap.policy.common.utils.coder.CoderException; -import org.onap.policy.common.utils.coder.StandardCoder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class instantiates the Apex Engine based on instruction from PAP. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class ApexEngineHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(ApexEngineHandler.class); - - private ApexMain apexMain; - - /** - * Constructs the object. Extracts the apex config and model files and instantiates the apex engine. - * - * @param properties - * @return ApexEngineHandler - * @throws ApexStarterException - */ - - public ApexEngineHandler(final String properties) throws ApexStarterException { - final StandardCoder standardCoder = new StandardCoder(); - JsonObject body; - try { - body = standardCoder.decode(new StringReader(properties), JsonObject.class); - } catch (final CoderException e) { - throw new ApexStarterException(e); - } - final JsonObject engineServiceParameters = body.get("engineServiceParameters").getAsJsonObject(); - final String policyModel = engineServiceParameters.get("policy_type_impl").toString(); - engineServiceParameters.remove("policy_type_impl"); - final String apexConfig = body.toString(); - - final String modelFilePath = createFile(policyModel, "modelFile"); - - final String apexConfigFilePath = createFile(apexConfig, "apexConfigFile"); - final String[] apexArgs = { "-rfr", "target/classes", "-c", apexConfigFilePath, "-m", modelFilePath }; - LOGGER.debug("Starting apex engine."); - apexMain = new ApexMain(apexArgs); - } - - /** - * Method to create the policy model file - * - * @param policyModel - * @param modelFilePath - * @throws ApexStarterException - */ - private String createFile(final String fileContent, final String fileName) throws ApexStarterException { - try { - final Path path = Files.createTempFile(fileName, ".json"); - Files.write(path, fileContent.getBytes(StandardCharsets.UTF_8)); - return path.toAbsolutePath().toString(); - } catch (final IOException e) { - final String errorMessage = "error creating from the properties received in PdpUpdate."; - LOGGER.error(errorMessage, e); - throw new ApexStarterException(errorMessage, e); - } - } - - public boolean isApexEngineRunning() { - return null != apexMain; - } - - public void shutdown() throws ApexStarterException { - try { - LOGGER.debug("Shutting down apex engine."); - apexMain.shutdown(); - apexMain = null; - } catch (final ApexException e) { - throw new ApexStarterException(e); - } - } -} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/exception/ApexStarterException.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/exception/ApexStarterException.java deleted file mode 100644 index 7062e377b..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/exception/ApexStarterException.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============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.apex.starter.exception; - -/** - * This exception will be called if an error occurs in apex starter. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class ApexStarterException extends Exception { - private static final long serialVersionUID = -510646141043975917L; - - /** - * Instantiates a new apex starter exception with a message. - * - * @param message the message - */ - public ApexStarterException(final String message) { - super(message); - } - - /** - * Instantiates a new apex starter exception caused by an exception. - * - * @param exception the exception that caused this exception to be thrown - */ - public ApexStarterException(final Exception exception) { - super(exception); - } - - /** - * Instantiates a new apex starter 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 ApexStarterException(final String message, final Exception exception) { - super(message, exception); - } - -} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/exception/ApexStarterRunTimeException.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/exception/ApexStarterRunTimeException.java deleted file mode 100644 index f15b55d33..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/exception/ApexStarterRunTimeException.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============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.apex.starter.exception; - -/** - * This runtime exception will be called if a runtime error occurs when using apex starter. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class ApexStarterRunTimeException extends RuntimeException { - private static final long serialVersionUID = -6024353312002272098L; - - /** - * Instantiates a new apex starter runtime exception with a message. - * - * @param message the message - */ - public ApexStarterRunTimeException(final String message) { - super(message); - } - - /** - * Instantiates a new apex starter runtime exception caused by an exception. - * - * @param exception the exception that caused this exception to be thrown - */ - public ApexStarterRunTimeException(final Exception exception) { - super(exception); - } - - /** - * Instantiates a new apex starter 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 ApexStarterRunTimeException(final String message, final Exception exception) { - super(message, exception); - } -} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/handler/PdpMessageHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/handler/PdpMessageHandler.java deleted file mode 100644 index be76938f3..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/handler/PdpMessageHandler.java +++ /dev/null @@ -1,152 +0,0 @@ -/*- - * ============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.apex.starter.handler; - -import java.util.ArrayList; -import java.util.List; - -import org.onap.policy.apex.starter.ApexStarterConstants; -import org.onap.policy.apex.starter.parameters.PdpStatusParameters; -import org.onap.policy.apex.starter.parameters.ToscaPolicyTypeIdentifierParameters; -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.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 apex 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 - * @return 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 apex-pdp to pap. - * - * @return PdpStatus the pdp status message - */ - public PdpStatus createPdpStatusFromContext() { - final PdpStatus pdpStatusContext = Registry.get(ApexStarterConstants.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 apex started is shutting down. - * - * @param policies list of ToscaPolicy - * - * @return PdpStatus - */ - public PdpStatus getTerminatedPdpStatus() { - final PdpStatus pdpStatusInContext = Registry.get(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); - pdpStatusInContext.setState(PdpState.TERMINATED); - pdpStatusInContext.setDescription("Apex pdp 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/services/services-onappf/src/main/java/org/onap/policy/apex/starter/handler/PdpStateChangeMessageHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/handler/PdpStateChangeMessageHandler.java deleted file mode 100644 index 9f97fb24b..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/handler/PdpStateChangeMessageHandler.java +++ /dev/null @@ -1,139 +0,0 @@ -/*- - * ============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.apex.starter.handler; - -import java.util.List; - -import org.onap.policy.apex.starter.ApexStarterConstants; -import org.onap.policy.apex.starter.comm.PdpStatusPublisher; -import org.onap.policy.apex.starter.engine.ApexEngineHandler; -import org.onap.policy.apex.starter.exception.ApexStarterException; -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.tosca.authorative.concepts.ToscaPolicy; - -/** - * This class supports the handling of pdp state change messages. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class PdpStateChangeMessageHandler { - - /** - * 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(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); - final PdpStatusPublisher pdpStatusPublisher = Registry.get(ApexStarterConstants.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 - * @param pdpStatusContext - * @param pdpMessageHandler - * @return pdpResponseDetails - */ - 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(ApexStarterConstants.REG_APEX_TOSCA_POLICY_LIST); - if (policies.isEmpty()) { - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), - PdpResponseStatus.SUCCESS, "No policies found. Apex engine not running."); - } else { - try { - // assumed that the apex policies list contains only one entry. - final ApexEngineHandler apexEngineHandler = - new ApexEngineHandler((String) policies.get(0).getProperties().get("content")); - Registry.registerOrReplace(ApexStarterConstants.REG_APEX_ENGINE_HANDLER, apexEngineHandler); - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), - PdpResponseStatus.SUCCESS, "Apex engine started. State changed to active."); - pdpStatusContext.setState(PdpState.ACTIVE); - } catch (final ApexStarterException e) { - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), - PdpResponseStatus.FAIL, "Apex engine service running failed. " + e.getMessage()); - } - } - } - return pdpResponseDetails; - } - - /** - * Method to handle when the new state from pap is passive. - * - * @param pdpStateChangeMsg - * @param pdpStatusContext - * @param pdpMessageHandler - * @return pdpResponseDetails - */ - 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 { - final ApexEngineHandler apexEngineHandler = Registry.get(ApexStarterConstants.REG_APEX_ENGINE_HANDLER); - try { - apexEngineHandler.shutdown(); - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), - PdpResponseStatus.SUCCESS, "Apex pdp state changed from Active to Passive."); - pdpStatusContext.setState(PdpState.PASSIVE); - } catch (final Exception e) { - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpStateChangeMsg.getRequestId(), - PdpResponseStatus.FAIL, - "Stopping apex engine failed. State cannot be changed to Passive." + e.getMessage()); - } - } - return pdpResponseDetails; - } -} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/handler/PdpUpdateMessageHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/handler/PdpUpdateMessageHandler.java deleted file mode 100644 index 5198c229e..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/handler/PdpUpdateMessageHandler.java +++ /dev/null @@ -1,164 +0,0 @@ -/*- - * ============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.apex.starter.handler; - -import java.util.List; - -import org.onap.policy.apex.starter.ApexStarterConstants; -import org.onap.policy.apex.starter.comm.PdpStatusPublisher; -import org.onap.policy.apex.starter.engine.ApexEngineHandler; -import org.onap.policy.apex.starter.exception.ApexStarterException; -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; - -/** - * This class supports the handling of pdp update messages. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class PdpUpdateMessageHandler { - - /** - * 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(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class); - PdpResponseDetails pdpResponseDetails = null; - if (pdpUpdateMsg.appliesTo(pdpStatusContext.getName(), pdpStatusContext.getPdpGroup(), - pdpStatusContext.getPdpSubgroup())) { - final PdpStatusPublisher pdpStatusPublisher = Registry.get(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER); - if (checkIfAlreadyHandled(pdpUpdateMsg, pdpStatusContext, pdpStatusPublisher.getInterval())) { - 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)) { - pdpResponseDetails = - startOrStopApexEngineBasedOnPolicies(pdpUpdateMsg, pdpMessageHandler, pdpStatusContext); - } - Registry.registerOrReplace(ApexStarterConstants.REG_APEX_TOSCA_POLICY_LIST, pdpUpdateMsg.getPolicies()); - if (null == pdpResponseDetails) { - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), - PdpResponseStatus.SUCCESS, "Pdp update successful."); - } - } - final PdpStatusPublisher pdpStatusPublisherTemp = - Registry.get(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER); - final PdpStatus pdpStatus = pdpMessageHandler.createPdpStatusFromContext(); - pdpStatus.setResponse(pdpResponseDetails); - pdpStatus.setDescription("Pdp status response message for PdpUpdate"); - pdpStatusPublisherTemp.send(pdpStatus); - } - } - - /** - * Method to start or stop apex engine based on the list of policies received from pap. When current state is - * active, if PAP sends PdpUpdate with empty policies list, stop apex engine, or, if there is a change in policies, - * stop the current running policies and the deploy the new ones. - * - * @param pdpUpdateMsg - * @param pdpMessageHandler - * @param pdpStatusContext - * @return pdpResponseDetails - */ - private PdpResponseDetails startOrStopApexEngineBasedOnPolicies(final PdpUpdate pdpUpdateMsg, - final PdpMessageHandler pdpMessageHandler, final PdpStatus pdpStatusContext) { - PdpResponseDetails pdpResponseDetails = null; - if (pdpUpdateMsg.getPolicies().isEmpty()) { - final ApexEngineHandler apexEngineHandler = Registry.get(ApexStarterConstants.REG_APEX_ENGINE_HANDLER); - if (apexEngineHandler.isApexEngineRunning()) { - try { - apexEngineHandler.shutdown(); - } catch (final ApexStarterException e) { - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), - PdpResponseStatus.FAIL, "Pdp update failed as the policies couldn't be undeployed."); - } - } - } else { - try { - ApexEngineHandler apexEngineHandler = Registry.get(ApexStarterConstants.REG_APEX_ENGINE_HANDLER); - if (apexEngineHandler.isApexEngineRunning()) { - apexEngineHandler.shutdown(); - } - apexEngineHandler = new ApexEngineHandler( - (String) pdpUpdateMsg.getPolicies().get(0).getProperties().get("content")); - Registry.registerOrReplace(ApexStarterConstants.REG_APEX_ENGINE_HANDLER, apexEngineHandler); - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), - PdpResponseStatus.SUCCESS, "Apex engine started and policies are running."); - } catch (final ApexStarterException e) { - pdpResponseDetails = pdpMessageHandler.createPdpResonseDetails(pdpUpdateMsg.getRequestId(), - PdpResponseStatus.FAIL, "Apex engine service running failed. " + e.getMessage()); - } - } - return pdpResponseDetails; - } - - /** - * Method checks of 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 - * @param interval the current interval in which the pdp status publisher is sending the heartbeats - * @return boolean flag which tells if the information is same or not - */ - private boolean checkIfAlreadyHandled(final PdpUpdate pdpUpdateMsg, final PdpStatus pdpStatusContext, - final long interval) { - 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()) - && (null == pdpUpdateMsg.getPdpHeartbeatIntervalMs() - || (null != pdpUpdateMsg.getPdpHeartbeatIntervalMs() - && pdpUpdateMsg.getPdpHeartbeatIntervalMs() > 0 - && interval == pdpUpdateMsg.getPdpHeartbeatIntervalMs())); - } - - /** - * 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(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER); - pdpStatusPublisher.terminate(); - final List topicSinks = Registry.get(ApexStarterConstants.REG_APEX_PDP_TOPIC_SINKS); - Registry.registerOrReplace(ApexStarterConstants.REG_PDP_STATUS_PUBLISHER, - new PdpStatusPublisher(topicSinks, interval)); - } -} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/ApexStarterParameterGroup.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/ApexStarterParameterGroup.java deleted file mode 100644 index 68299480e..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/ApexStarterParameterGroup.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============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.apex.starter.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 apex starter component. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -@NotNull -@NotBlank -@Getter -public class ApexStarterParameterGroup extends ParameterGroupImpl { - - private PdpStatusParameters pdpStatusParameters; - - /** - * Create the apex starter parameter group. - * - * @param name the parameter group name - */ - public ApexStarterParameterGroup(final String name) { - super(name); - } -} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/ApexStarterParameterHandler.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/ApexStarterParameterHandler.java deleted file mode 100644 index dae4b8334..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/ApexStarterParameterHandler.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============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.apex.starter.parameters; - -import java.io.File; - -import org.onap.policy.apex.starter.ApexStarterCommandLineArguments; -import org.onap.policy.apex.starter.exception.ApexStarterException; -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.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class handles reading, parsing and validating of apex starter parameters from JSON files. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class ApexStarterParameterHandler { - - private static final Logger LOGGER = LoggerFactory.getLogger(ApexStarterParameterHandler.class); - private static final Coder CODER = new StandardCoder(); - - /** - * Read the parameters from the parameter file. - * - * @param arguments the arguments passed to apex starter - * @return the parameters read from the configuration file - * @throws ApexStarterException on parameter exceptions - */ - public ApexStarterParameterGroup getParameters(final ApexStarterCommandLineArguments arguments) - throws ApexStarterException { - ApexStarterParameterGroup apexStarterParameterGroup = null; - - // Read the parameters - try { - // Read the parameters from JSON - final File file = new File(arguments.getFullConfigurationFilePath()); - apexStarterParameterGroup = CODER.decode(file, ApexStarterParameterGroup.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 ApexStarterException(errorMessage, e); - } - - // The JSON processing returns null if there is an empty file - if (apexStarterParameterGroup == null) { - final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\""; - LOGGER.error(errorMessage); - throw new ApexStarterException(errorMessage); - } - - // validate the parameters - final GroupValidationResult validationResult = apexStarterParameterGroup.validate(); - if (!validationResult.isValid()) { - String returnMessage = - "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n"; - returnMessage += validationResult.getResult(); - - LOGGER.error(returnMessage); - throw new ApexStarterException(returnMessage); - } - - return apexStarterParameterGroup; - } - -} diff --git a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/PdpStatusParameters.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/PdpStatusParameters.java deleted file mode 100644 index fbc94193d..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/PdpStatusParameters.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============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.apex.starter.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/services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/ToscaPolicyTypeIdentifierParameters.java b/services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/ToscaPolicyTypeIdentifierParameters.java deleted file mode 100644 index 37e27492e..000000000 --- a/services/services-onappf/src/main/java/org/onap/policy/apex/starter/parameters/ToscaPolicyTypeIdentifierParameters.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============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.apex.starter.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/services/services-onappf/src/main/resources/config/OnapPfConfig.json b/services/services-onappf/src/main/resources/config/OnapPfConfig.json new file mode 100644 index 000000000..5684f1d4e --- /dev/null +++ b/services/services-onappf/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","version":"1.0.0"}] + } +} \ No newline at end of file diff --git a/services/services-onappf/src/main/resources/config/topic.properties b/services/services-onappf/src/main/resources/config/topic.properties new file mode 100644 index 000000000..b61626b2d --- /dev/null +++ b/services/services-onappf/src/main/resources/config/topic.properties @@ -0,0 +1,23 @@ +# ============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 +dmaap.sink.topics.POLICY-PDP-PAP.servers= message-router \ No newline at end of file diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterActivator.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterActivator.java new file mode 100644 index 000000000..238a89f66 --- /dev/null +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterActivator.java @@ -0,0 +1,120 @@ +/*- + * ============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.apex.services.onappf; + +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.apex.services.onappf.ApexStarterActivator; +import org.onap.policy.apex.services.onappf.ApexStarterCommandLineArguments; +import org.onap.policy.apex.services.onappf.ApexStarterConstants; +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup; +import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterHandler; +import org.onap.policy.apex.services.onappf.parameters.CommonTestData; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.pdp.concepts.PdpStatus; + +/** + * Class to perform unit test of {@link ApexStarterActivator}}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestApexStarterActivator { + + private ApexStarterActivator activator; + + /** + * Initializes an activator. + * + * @throws Exception if an error occurs + */ + @Before + public void setUp() throws Exception { + Registry.newRegistry(); + final String[] apexStarterConfigParameters = { "-c", "src/test/resources/ApexStarterConfigParameters.json", + "-p", "src/test/resources/topic.properties" }; + final ApexStarterCommandLineArguments arguments = + new ApexStarterCommandLineArguments(apexStarterConfigParameters); + final ApexStarterParameterGroup parGroup = new ApexStarterParameterHandler().getParameters(arguments); + + final Properties props = new Properties(); + final String propFile = arguments.getFullPropertyFilePath(); + try (FileInputStream stream = new FileInputStream(propFile)) { + props.load(stream); + } + + activator = new ApexStarterActivator(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 testApexStarterActivator() throws ApexStarterException { + assertFalse(activator.isAlive()); + activator.initialize(); + assertTrue(activator.isAlive()); + assertTrue(activator.getParameterGroup().isValid()); + assertEquals(CommonTestData.APEX_STARTER_GROUP_NAME, activator.getParameterGroup().getName()); + + // ensure items were added to the registry + assertNotNull(Registry.get(ApexStarterConstants.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(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class, null)); + + // repeat - should throw an exception + assertThatIllegalStateException().isThrownBy(() -> activator.terminate()); + assertFalse(activator.isAlive()); + } +} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterConstants.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterConstants.java new file mode 100644 index 000000000..52ca94439 --- /dev/null +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterConstants.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.apex.services.onappf; + +import org.junit.Test; +import org.onap.policy.apex.services.onappf.ApexStarterConstants; +import org.powermock.reflect.Whitebox; + +/** + * Class to perform unit test of {@link ApexStarterConstants}}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestApexStarterConstants { + @Test + public void test() throws Exception { + // verify that constructor does not throw an exception + Whitebox.invokeConstructor(ApexStarterConstants.class); + } +} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterMain.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterMain.java new file mode 100644 index 000000000..c5c0fc483 --- /dev/null +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/TestApexStarterMain.java @@ -0,0 +1,109 @@ +/*- + * ============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.apex.services.onappf; + +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.apex.services.onappf.ApexStarterActivator; +import org.onap.policy.apex.services.onappf.ApexStarterConstants; +import org.onap.policy.apex.services.onappf.ApexStarterMain; +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +import org.onap.policy.apex.services.onappf.parameters.CommonTestData; +import org.onap.policy.common.utils.services.Registry; + +/** + * Class to perform unit test of {@link ApexStarterMain}}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestApexStarterMain { + private ApexStarterMain apexStarter; + + /** + * 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 ApexStarterActivator activator = Registry.getOrDefault(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, + ApexStarterActivator.class, null); + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } + + @Test + public void testApexStarter() throws ApexStarterException { + final String[] apexStarterConfigParameters = { "-c", "src/test/resources/ApexStarterConfigParameters.json", + "-p", "src/test/resources/topic.properties" }; + apexStarter = new ApexStarterMain(apexStarterConfigParameters); + assertTrue(apexStarter.getParameters().isValid()); + assertEquals(CommonTestData.APEX_STARTER_GROUP_NAME, apexStarter.getParameters().getName()); + + // ensure items were added to the registry + assertNotNull(Registry.get(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, ApexStarterActivator.class)); + + apexStarter.shutdown(); + } + + @Test + public void testApexStarter_NoArguments() { + final String[] apexStarterConfigParameters = {}; + apexStarter = new ApexStarterMain(apexStarterConfigParameters); + assertTrue(apexStarter.getParameters() == null); + } + + @Test + public void testApexStarter_InvalidArguments() { + final String[] apexStarterConfigParameters = { "src/test/resources/ApexStarterConfigParameters.json" }; + apexStarter = new ApexStarterMain(apexStarterConfigParameters); + assertTrue(apexStarter.getParameters() == null); + } + + @Test + public void testApexStarter_Help() { + final String[] apexStarterConfigParameters = { "-h" }; + ApexStarterMain.main(apexStarterConfigParameters); + } + + @Test + public void testApexStarter_InvalidParameters() { + final String[] apexStarterConfigParameters = + { "-c", "src/test/resources/ApexStarterConfigParameters_InvalidName.json" }; + apexStarter = new ApexStarterMain(apexStarterConfigParameters); + assertTrue(apexStarter.getParameters() == null); + } +} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpStateChangeListener.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpStateChangeListener.java new file mode 100644 index 000000000..34025a1ad --- /dev/null +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpStateChangeListener.java @@ -0,0 +1,173 @@ +/*- + * ============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.apex.services.onappf.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.apex.services.onappf.ApexStarterActivator; +import org.onap.policy.apex.services.onappf.ApexStarterCommandLineArguments; +import org.onap.policy.apex.services.onappf.ApexStarterConstants; +import org.onap.policy.apex.services.onappf.comm.PdpStateChangeListener; +import org.onap.policy.apex.services.onappf.comm.PdpUpdateListener; +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup; +import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterHandler; +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.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 ApexStarterActivator activator; + + @Before + public void setUp() throws ApexStarterException, FileNotFoundException, IOException { + pdpUpdateMessageListener = new PdpUpdateListener(); + pdpStateChangeListener = new PdpStateChangeListener(); + Registry.newRegistry(); + final String[] apexStarterConfigParameters = { "-c", "src/test/resources/ApexStarterConfigParameters.json", + "-p", "src/test/resources/topic.properties" }; + final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); + ApexStarterParameterGroup apexStarterParameterGroup; + // The arguments return a string if there is a message to print and we should + // exit + final String argumentMessage = arguments.parse(apexStarterConfigParameters); + if (argumentMessage != null) { + return; + } + // Validate that the arguments are sane + arguments.validate(); + + // Read the parameters + apexStarterParameterGroup = new ApexStarterParameterHandler().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 ApexStarterActivator(apexStarterParameterGroup, topicProperties); + Registry.register(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, activator); + activator.initialize(); + } + + /** + * Method for cleanup after each test. + * + * @throws Exception if an error occurs + */ + @After + public void teardown() throws Exception { + + // clear the apex starter activator + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } + + /** + * @param instance + * @return + */ + 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(ApexStarterConstants.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(ApexStarterConstants.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/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpUpdateListener.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpUpdateListener.java new file mode 100644 index 000000000..921cfd283 --- /dev/null +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/comm/TestPdpUpdateListener.java @@ -0,0 +1,142 @@ +/*- + * ============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.apex.services.onappf.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.apex.services.onappf.ApexStarterActivator; +import org.onap.policy.apex.services.onappf.ApexStarterCommandLineArguments; +import org.onap.policy.apex.services.onappf.ApexStarterConstants; +import org.onap.policy.apex.services.onappf.comm.PdpUpdateListener; +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +import org.onap.policy.apex.services.onappf.handler.PdpMessageHandler; +import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup; +import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterHandler; +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.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 ApexStarterActivator activator; + + @Before + public void setUp() throws ApexStarterException, FileNotFoundException, IOException { + Registry.newRegistry(); + final String[] apexStarterConfigParameters = { "-c", "src/test/resources/ApexStarterConfigParameters.json", + "-p", "src/test/resources/topic.properties" }; + final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); + ApexStarterParameterGroup apexStarterParameterGroup; + // The arguments return a string if there is a message to print and we should + // exit + final String argumentMessage = arguments.parse(apexStarterConfigParameters); + if (argumentMessage != null) { + return; + } + // Validate that the arguments are sane + arguments.validate(); + + // Read the parameters + apexStarterParameterGroup = new ApexStarterParameterHandler().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 ApexStarterActivator(apexStarterParameterGroup, topicProperties); + Registry.register(ApexStarterConstants.REG_APEX_STARTER_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 apex starter activator + if (activator != null && activator.isAlive()) { + activator.terminate(); + } + } + + @Test + public void testPdpUpdateMssageListener() { + final PdpStatus pdpStatus = Registry.get(ApexStarterConstants.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/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/exception/TestExceptions.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/exception/TestExceptions.java new file mode 100644 index 000000000..3a05e72b1 --- /dev/null +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/exception/TestExceptions.java @@ -0,0 +1,40 @@ +/*- + * ============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.apex.services.onappf.exception; + +import org.junit.Test; +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +import org.onap.policy.apex.services.onappf.exception.ApexStarterRunTimeException; +import org.onap.policy.common.utils.test.ExceptionsTester; + +/** + * Class to perform unit test of {@link ApexStarterException ApexStarterRunTimeException}}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestExceptions { + + @Test + public void test() { + new ExceptionsTester().test(ApexStarterException.class); + new ExceptionsTester().test(ApexStarterRunTimeException.class); + } +} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/CommonTestData.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/CommonTestData.java new file mode 100644 index 000000000..e4946dd2b --- /dev/null +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/CommonTestData.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.apex.services.onappf.parameters; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.onap.policy.apex.services.onappf.parameters.ToscaPolicyTypeIdentifierParameters; +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 APEX_STARTER_GROUP_NAME = "ApexStarterParameterGroup"; + 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)); + + 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 ApexStarterParameterGroup map for test cases. + * + * @param name name of the parameters + * + * @return a property map suitable for constructing an object + */ + public Map getApexStarterParameterGroupMap(final String name) { + final Map map = new TreeMap<>(); + + map.put("name", name); + map.put("pdpStatusParameters", getPdpStatusParametersMap(false)); + + 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/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterGroup.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterGroup.java new file mode 100644 index 000000000..c843c6787 --- /dev/null +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterGroup.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.apex.services.onappf.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 ApexStarterParameterGroup}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestApexStarterParameterGroup { + CommonTestData commonTestData = new CommonTestData(); + + @Test + public void testApexStarterParameterGroup_Named() { + final ApexStarterParameterGroup apexStarterParameters = new ApexStarterParameterGroup("my-name"); + assertEquals("my-name", apexStarterParameters.getName()); + } + + @Test + public void testApexStarterParameterGroup() { + final ApexStarterParameterGroup apexStarterParameters = commonTestData.toObject( + commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME), + ApexStarterParameterGroup.class); + final PdpStatusParameters pdpStatusParameters = apexStarterParameters.getPdpStatusParameters(); + final GroupValidationResult validationResult = apexStarterParameters.validate(); + assertTrue(validationResult.isValid()); + assertEquals(CommonTestData.APEX_STARTER_GROUP_NAME, apexStarterParameters.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 testApexStarterParameterGroup_NullName() { + final ApexStarterParameterGroup apexStarterParameters = commonTestData + .toObject(commonTestData.getApexStarterParameterGroupMap(null), ApexStarterParameterGroup.class); + final GroupValidationResult validationResult = apexStarterParameters.validate(); + assertFalse(validationResult.isValid()); + assertEquals(null, apexStarterParameters.getName()); + assertTrue(validationResult.getResult().contains("is null")); + } + + @Test + public void testApexStarterParameterGroup_EmptyName() { + final ApexStarterParameterGroup apexStarterParameters = commonTestData + .toObject(commonTestData.getApexStarterParameterGroupMap(""), ApexStarterParameterGroup.class); + final GroupValidationResult validationResult = apexStarterParameters.validate(); + assertFalse(validationResult.isValid()); + assertEquals("", apexStarterParameters.getName()); + assertTrue(validationResult.getResult().contains( + "field \"name\" type \"java.lang.String\" value \"\" INVALID, " + "must be a non-blank string")); + } + + @Test + public void testApexStarterParameterGroup_SetName() { + final ApexStarterParameterGroup apexStarterParameters = commonTestData.toObject( + commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME), + ApexStarterParameterGroup.class); + apexStarterParameters.setName("ApexStarterNewGroup"); + final GroupValidationResult validationResult = apexStarterParameters.validate(); + assertTrue(validationResult.isValid()); + assertEquals("ApexStarterNewGroup", apexStarterParameters.getName()); + } + + @Test + public void testApexStarterParameterGroup_EmptyPdpStatusParameters() { + final Map map = + commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME); + map.put("pdpStatusParameters", commonTestData.getPdpStatusParametersMap(true)); + final ApexStarterParameterGroup apexStarterParameters = + commonTestData.toObject(map, ApexStarterParameterGroup.class); + final GroupValidationResult validationResult = apexStarterParameters.validate(); + assertFalse(validationResult.isValid()); + assertTrue(validationResult.getResult() + .contains("\"org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup\" INVALID, " + + "parameter group has status INVALID")); + } +} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterHandler.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterHandler.java new file mode 100644 index 000000000..f91baeb45 --- /dev/null +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestApexStarterParameterHandler.java @@ -0,0 +1,159 @@ +/*- + * ============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.apex.services.onappf.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.apex.services.onappf.ApexStarterCommandLineArguments; +import org.onap.policy.apex.services.onappf.exception.ApexStarterException; +import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterGroup; +import org.onap.policy.apex.services.onappf.parameters.ApexStarterParameterHandler; +import org.onap.policy.common.utils.coder.CoderException; + +/** + * Class to perform unit test of {@link ApexStarterParameterHandler}. + * + * @author Ajith Sreekumar (ajith.sreekumar@est.tech) + */ +public class TestApexStarterParameterHandler { + + @Test + public void testParameterHandlerNoParameterFile() throws ApexStarterException { + final String[] emptyArgumentString = { "-c", "src/test/resources/NoParametersFile.json" }; + + final ApexStarterCommandLineArguments emptyArguments = new ApexStarterCommandLineArguments(); + emptyArguments.parse(emptyArgumentString); + + try { + new ApexStarterParameterHandler().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 ApexStarterException { + final String[] noArgumentString = { "-c", "src/test/resources/NoParameters.json" }; + + final ApexStarterCommandLineArguments noArguments = new ApexStarterCommandLineArguments(); + noArguments.parse(noArgumentString); + + try { + new ApexStarterParameterHandler().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 ApexStarterException { + final String[] invalidArgumentString = { "-c", "src/test/resources/InvalidParameters.json" }; + + final ApexStarterCommandLineArguments invalidArguments = new ApexStarterCommandLineArguments(); + invalidArguments.parse(invalidArgumentString); + + try { + new ApexStarterParameterHandler().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 ApexStarterException { + final String[] noArgumentString = { "-c", "src/test/resources/EmptyConfigParameters.json" }; + + final ApexStarterCommandLineArguments noArguments = new ApexStarterCommandLineArguments(); + noArguments.parse(noArgumentString); + + try { + new ApexStarterParameterHandler().getParameters(noArguments); + } catch (final Exception e) { + assertTrue(e.getMessage().contains("is null")); + } + } + + @Test + public void testApexStarterParameterGroup() throws ApexStarterException { + final String[] apexStarterConfigParameters = { "-c", "src/test/resources/ApexStarterConfigParameters.json" }; + + final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); + arguments.parse(apexStarterConfigParameters); + + final ApexStarterParameterGroup parGroup = new ApexStarterParameterHandler().getParameters(arguments); + assertTrue(arguments.checkSetConfigurationFilePath()); + assertEquals(CommonTestData.APEX_STARTER_GROUP_NAME, parGroup.getName()); + } + + @Test + public void testApexStarterParameterGroup_InvalidName() throws ApexStarterException { + final String[] apexStarterConfigParameters = + { "-c", "src/test/resources/ApexStarterConfigParameters_InvalidName.json" }; + + final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); + arguments.parse(apexStarterConfigParameters); + + try { + new ApexStarterParameterHandler().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 testApexStarterVersion() throws ApexStarterException { + final String[] apexStarterConfigParameters = { "-v" }; + final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); + final String version = arguments.parse(apexStarterConfigParameters); + assertTrue(version.startsWith("ONAP Policy Framework Apex Starter Service")); + } + + @Test + public void testApexStarterHelp() throws ApexStarterException { + final String[] apexStarterConfigParameters = { "-h" }; + final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); + final String help = arguments.parse(apexStarterConfigParameters); + assertTrue(help.startsWith("usage:")); + } + + @Test + public void testApexStarterInvalidOption() throws ApexStarterException { + final String[] apexStarterConfigParameters = { "-d" }; + final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); + try { + arguments.parse(apexStarterConfigParameters); + } catch (final Exception exp) { + assertTrue(exp.getMessage().startsWith("invalid command line arguments specified")); + } + } +} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestPdpStatusParameters.java b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestPdpStatusParameters.java new file mode 100644 index 000000000..e8a3f7ee0 --- /dev/null +++ b/services/services-onappf/src/test/java/org/onap/policy/apex/services/onappf/parameters/TestPdpStatusParameters.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.apex.services.onappf.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.apex.services.onappf.parameters.PdpStatusParameters; +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/services/services-onappf/src/test/java/org/onap/policy/apex/starter/TestApexStarterActivator.java b/services/services-onappf/src/test/java/org/onap/policy/apex/starter/TestApexStarterActivator.java deleted file mode 100644 index 6da3a5eb6..000000000 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/TestApexStarterActivator.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============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.apex.starter; - -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.apex.starter.exception.ApexStarterException; -import org.onap.policy.apex.starter.parameters.ApexStarterParameterGroup; -import org.onap.policy.apex.starter.parameters.ApexStarterParameterHandler; -import org.onap.policy.apex.starter.parameters.CommonTestData; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.pdp.concepts.PdpStatus; - -/** - * Class to perform unit test of {@link ApexStarterActivator}}. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class TestApexStarterActivator { - - private ApexStarterActivator activator; - - /** - * Initializes an activator. - * - * @throws Exception if an error occurs - */ - @Before - public void setUp() throws Exception { - Registry.newRegistry(); - final String[] apexStarterConfigParameters = { "-c", "src/test/resources/ApexStarterConfigParameters.json", - "-p", "src/test/resources/topic.properties" }; - final ApexStarterCommandLineArguments arguments = - new ApexStarterCommandLineArguments(apexStarterConfigParameters); - final ApexStarterParameterGroup parGroup = new ApexStarterParameterHandler().getParameters(arguments); - - final Properties props = new Properties(); - final String propFile = arguments.getFullPropertyFilePath(); - try (FileInputStream stream = new FileInputStream(propFile)) { - props.load(stream); - } - - activator = new ApexStarterActivator(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 testApexStarterActivator() throws ApexStarterException { - assertFalse(activator.isAlive()); - activator.initialize(); - assertTrue(activator.isAlive()); - assertTrue(activator.getParameterGroup().isValid()); - assertEquals(CommonTestData.APEX_STARTER_GROUP_NAME, activator.getParameterGroup().getName()); - - // ensure items were added to the registry - assertNotNull(Registry.get(ApexStarterConstants.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(ApexStarterConstants.REG_PDP_STATUS_OBJECT, PdpStatus.class, null)); - - // repeat - should throw an exception - assertThatIllegalStateException().isThrownBy(() -> activator.terminate()); - assertFalse(activator.isAlive()); - } -} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/TestApexStarterConstants.java b/services/services-onappf/src/test/java/org/onap/policy/apex/starter/TestApexStarterConstants.java deleted file mode 100644 index 08e56cdf8..000000000 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/TestApexStarterConstants.java +++ /dev/null @@ -1,37 +0,0 @@ -/*- - * ============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.apex.starter; - -import org.junit.Test; -import org.powermock.reflect.Whitebox; - -/** - * Class to perform unit test of {@link ApexStarterConstants}}. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class TestApexStarterConstants { - @Test - public void test() throws Exception { - // verify that constructor does not throw an exception - Whitebox.invokeConstructor(ApexStarterConstants.class); - } -} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/TestApexStarterMain.java b/services/services-onappf/src/test/java/org/onap/policy/apex/starter/TestApexStarterMain.java deleted file mode 100644 index 3005e320a..000000000 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/TestApexStarterMain.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============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.apex.starter; - -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.apex.starter.exception.ApexStarterException; -import org.onap.policy.apex.starter.parameters.CommonTestData; -import org.onap.policy.common.utils.services.Registry; - -/** - * Class to perform unit test of {@link ApexStarterMain}}. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class TestApexStarterMain { - private ApexStarterMain apexStarter; - - /** - * 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 ApexStarterActivator activator = Registry.getOrDefault(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, - ApexStarterActivator.class, null); - if (activator != null && activator.isAlive()) { - activator.terminate(); - } - } - - @Test - public void testApexStarter() throws ApexStarterException { - final String[] apexStarterConfigParameters = { "-c", "src/test/resources/ApexStarterConfigParameters.json", - "-p", "src/test/resources/topic.properties" }; - apexStarter = new ApexStarterMain(apexStarterConfigParameters); - assertTrue(apexStarter.getParameters().isValid()); - assertEquals(CommonTestData.APEX_STARTER_GROUP_NAME, apexStarter.getParameters().getName()); - - // ensure items were added to the registry - assertNotNull(Registry.get(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, ApexStarterActivator.class)); - - apexStarter.shutdown(); - } - - @Test - public void testApexStarter_NoArguments() { - final String[] apexStarterConfigParameters = {}; - apexStarter = new ApexStarterMain(apexStarterConfigParameters); - assertTrue(apexStarter.getParameters() == null); - } - - @Test - public void testApexStarter_InvalidArguments() { - final String[] apexStarterConfigParameters = { "src/test/resources/ApexStarterConfigParameters.json" }; - apexStarter = new ApexStarterMain(apexStarterConfigParameters); - assertTrue(apexStarter.getParameters() == null); - } - - @Test - public void testApexStarter_Help() { - final String[] apexStarterConfigParameters = { "-h" }; - ApexStarterMain.main(apexStarterConfigParameters); - } - - @Test - public void testApexStarter_InvalidParameters() { - final String[] apexStarterConfigParameters = - { "-c", "src/test/resources/ApexStarterConfigParameters_InvalidName.json" }; - apexStarter = new ApexStarterMain(apexStarterConfigParameters); - assertTrue(apexStarter.getParameters() == null); - } -} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/comm/TestPdpStateChangeListener.java b/services/services-onappf/src/test/java/org/onap/policy/apex/starter/comm/TestPdpStateChangeListener.java deleted file mode 100644 index d0a85f9f2..000000000 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/comm/TestPdpStateChangeListener.java +++ /dev/null @@ -1,171 +0,0 @@ -/*- - * ============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.apex.starter.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.apex.starter.ApexStarterActivator; -import org.onap.policy.apex.starter.ApexStarterCommandLineArguments; -import org.onap.policy.apex.starter.ApexStarterConstants; -import org.onap.policy.apex.starter.exception.ApexStarterException; -import org.onap.policy.apex.starter.parameters.ApexStarterParameterGroup; -import org.onap.policy.apex.starter.parameters.ApexStarterParameterHandler; -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.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 ApexStarterActivator activator; - - @Before - public void setUp() throws ApexStarterException, FileNotFoundException, IOException { - pdpUpdateMessageListener = new PdpUpdateListener(); - pdpStateChangeListener = new PdpStateChangeListener(); - Registry.newRegistry(); - final String[] apexStarterConfigParameters = { "-c", "src/test/resources/ApexStarterConfigParameters.json", - "-p", "src/test/resources/topic.properties" }; - final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); - ApexStarterParameterGroup apexStarterParameterGroup; - // The arguments return a string if there is a message to print and we should - // exit - final String argumentMessage = arguments.parse(apexStarterConfigParameters); - if (argumentMessage != null) { - return; - } - // Validate that the arguments are sane - arguments.validate(); - - // Read the parameters - apexStarterParameterGroup = new ApexStarterParameterHandler().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 ApexStarterActivator(apexStarterParameterGroup, topicProperties); - Registry.register(ApexStarterConstants.REG_APEX_STARTER_ACTIVATOR, activator); - activator.initialize(); - } - - /** - * Method for cleanup after each test. - * - * @throws Exception if an error occurs - */ - @After - public void teardown() throws Exception { - - // clear the apex starter activator - if (activator != null && activator.isAlive()) { - activator.terminate(); - } - } - - /** - * @param instance - * @return - */ - 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(ApexStarterConstants.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(ApexStarterConstants.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/services/services-onappf/src/test/java/org/onap/policy/apex/starter/comm/TestPdpUpdateListener.java b/services/services-onappf/src/test/java/org/onap/policy/apex/starter/comm/TestPdpUpdateListener.java deleted file mode 100644 index 2ffed2cb6..000000000 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/comm/TestPdpUpdateListener.java +++ /dev/null @@ -1,141 +0,0 @@ -/*- - * ============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.apex.starter.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.apex.starter.ApexStarterActivator; -import org.onap.policy.apex.starter.ApexStarterCommandLineArguments; -import org.onap.policy.apex.starter.ApexStarterConstants; -import org.onap.policy.apex.starter.exception.ApexStarterException; -import org.onap.policy.apex.starter.handler.PdpMessageHandler; -import org.onap.policy.apex.starter.parameters.ApexStarterParameterGroup; -import org.onap.policy.apex.starter.parameters.ApexStarterParameterHandler; -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.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 ApexStarterActivator activator; - - @Before - public void setUp() throws ApexStarterException, FileNotFoundException, IOException { - Registry.newRegistry(); - final String[] apexStarterConfigParameters = { "-c", "src/test/resources/ApexStarterConfigParameters.json", - "-p", "src/test/resources/topic.properties" }; - final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); - ApexStarterParameterGroup apexStarterParameterGroup; - // The arguments return a string if there is a message to print and we should - // exit - final String argumentMessage = arguments.parse(apexStarterConfigParameters); - if (argumentMessage != null) { - return; - } - // Validate that the arguments are sane - arguments.validate(); - - // Read the parameters - apexStarterParameterGroup = new ApexStarterParameterHandler().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 ApexStarterActivator(apexStarterParameterGroup, topicProperties); - Registry.register(ApexStarterConstants.REG_APEX_STARTER_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 apex starter activator - if (activator != null && activator.isAlive()) { - activator.terminate(); - } - } - - @Test - public void testPdpUpdateMssageListener() { - final PdpStatus pdpStatus = Registry.get(ApexStarterConstants.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/services/services-onappf/src/test/java/org/onap/policy/apex/starter/exception/TestExceptions.java b/services/services-onappf/src/test/java/org/onap/policy/apex/starter/exception/TestExceptions.java deleted file mode 100644 index 63ebeb608..000000000 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/exception/TestExceptions.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============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.apex.starter.exception; - -import org.junit.Test; -import org.onap.policy.common.utils.test.ExceptionsTester; - -/** - * Class to perform unit test of {@link ApexStarterException ApexStarterRunTimeException}}. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class TestExceptions { - - @Test - public void test() { - new ExceptionsTester().test(ApexStarterException.class); - new ExceptionsTester().test(ApexStarterRunTimeException.class); - } -} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/CommonTestData.java b/services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/CommonTestData.java deleted file mode 100644 index d329d1f22..000000000 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/CommonTestData.java +++ /dev/null @@ -1,116 +0,0 @@ -/*- - * ============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.apex.starter.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 APEX_STARTER_GROUP_NAME = "ApexStarterParameterGroup"; - 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)); - - 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 ApexStarterParameterGroup map for test cases. - * - * @param name name of the parameters - * - * @return a property map suitable for constructing an object - */ - public Map getApexStarterParameterGroupMap(final String name) { - final Map map = new TreeMap<>(); - - map.put("name", name); - map.put("pdpStatusParameters", getPdpStatusParametersMap(false)); - - 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/services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/TestApexStarterParameterGroup.java b/services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/TestApexStarterParameterGroup.java deleted file mode 100644 index 8d5f1cef9..000000000 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/TestApexStarterParameterGroup.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============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.apex.starter.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 ApexStarterParameterGroup}. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class TestApexStarterParameterGroup { - CommonTestData commonTestData = new CommonTestData(); - - @Test - public void testApexStarterParameterGroup_Named() { - final ApexStarterParameterGroup apexStarterParameters = new ApexStarterParameterGroup("my-name"); - assertEquals("my-name", apexStarterParameters.getName()); - } - - @Test - public void testApexStarterParameterGroup() { - final ApexStarterParameterGroup apexStarterParameters = commonTestData.toObject( - commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME), - ApexStarterParameterGroup.class); - final PdpStatusParameters pdpStatusParameters = apexStarterParameters.getPdpStatusParameters(); - final GroupValidationResult validationResult = apexStarterParameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals(CommonTestData.APEX_STARTER_GROUP_NAME, apexStarterParameters.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 testApexStarterParameterGroup_NullName() { - final ApexStarterParameterGroup apexStarterParameters = commonTestData - .toObject(commonTestData.getApexStarterParameterGroupMap(null), ApexStarterParameterGroup.class); - final GroupValidationResult validationResult = apexStarterParameters.validate(); - assertFalse(validationResult.isValid()); - assertEquals(null, apexStarterParameters.getName()); - assertTrue(validationResult.getResult().contains("is null")); - } - - @Test - public void testApexStarterParameterGroup_EmptyName() { - final ApexStarterParameterGroup apexStarterParameters = commonTestData - .toObject(commonTestData.getApexStarterParameterGroupMap(""), ApexStarterParameterGroup.class); - final GroupValidationResult validationResult = apexStarterParameters.validate(); - assertFalse(validationResult.isValid()); - assertEquals("", apexStarterParameters.getName()); - assertTrue(validationResult.getResult().contains( - "field \"name\" type \"java.lang.String\" value \"\" INVALID, " + "must be a non-blank string")); - } - - @Test - public void testApexStarterParameterGroup_SetName() { - final ApexStarterParameterGroup apexStarterParameters = commonTestData.toObject( - commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME), - ApexStarterParameterGroup.class); - apexStarterParameters.setName("ApexStarterNewGroup"); - final GroupValidationResult validationResult = apexStarterParameters.validate(); - assertTrue(validationResult.isValid()); - assertEquals("ApexStarterNewGroup", apexStarterParameters.getName()); - } - - @Test - public void testApexStarterParameterGroup_EmptyPdpStatusParameters() { - final Map map = - commonTestData.getApexStarterParameterGroupMap(CommonTestData.APEX_STARTER_GROUP_NAME); - map.put("pdpStatusParameters", commonTestData.getPdpStatusParametersMap(true)); - final ApexStarterParameterGroup apexStarterParameters = - commonTestData.toObject(map, ApexStarterParameterGroup.class); - final GroupValidationResult validationResult = apexStarterParameters.validate(); - assertFalse(validationResult.isValid()); - assertTrue(validationResult.getResult() - .contains("\"org.onap.policy.apex.starter.parameters.ApexStarterParameterGroup\" INVALID, " - + "parameter group has status INVALID")); - } -} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/TestApexStarterParameterHandler.java b/services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/TestApexStarterParameterHandler.java deleted file mode 100644 index baa91d23a..000000000 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/TestApexStarterParameterHandler.java +++ /dev/null @@ -1,157 +0,0 @@ -/*- - * ============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.apex.starter.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.apex.starter.ApexStarterCommandLineArguments; -import org.onap.policy.apex.starter.exception.ApexStarterException; -import org.onap.policy.common.utils.coder.CoderException; - -/** - * Class to perform unit test of {@link ApexStarterParameterHandler}. - * - * @author Ajith Sreekumar (ajith.sreekumar@est.tech) - */ -public class TestApexStarterParameterHandler { - - @Test - public void testParameterHandlerNoParameterFile() throws ApexStarterException { - final String[] emptyArgumentString = { "-c", "src/test/resources/NoParametersFile.json" }; - - final ApexStarterCommandLineArguments emptyArguments = new ApexStarterCommandLineArguments(); - emptyArguments.parse(emptyArgumentString); - - try { - new ApexStarterParameterHandler().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 ApexStarterException { - final String[] noArgumentString = { "-c", "src/test/resources/NoParameters.json" }; - - final ApexStarterCommandLineArguments noArguments = new ApexStarterCommandLineArguments(); - noArguments.parse(noArgumentString); - - try { - new ApexStarterParameterHandler().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 ApexStarterException { - final String[] invalidArgumentString = { "-c", "src/test/resources/InvalidParameters.json" }; - - final ApexStarterCommandLineArguments invalidArguments = new ApexStarterCommandLineArguments(); - invalidArguments.parse(invalidArgumentString); - - try { - new ApexStarterParameterHandler().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 ApexStarterException { - final String[] noArgumentString = { "-c", "src/test/resources/EmptyConfigParameters.json" }; - - final ApexStarterCommandLineArguments noArguments = new ApexStarterCommandLineArguments(); - noArguments.parse(noArgumentString); - - try { - new ApexStarterParameterHandler().getParameters(noArguments); - } catch (final Exception e) { - assertTrue(e.getMessage().contains("is null")); - } - } - - @Test - public void testApexStarterParameterGroup() throws ApexStarterException { - final String[] apexStarterConfigParameters = { "-c", "src/test/resources/ApexStarterConfigParameters.json" }; - - final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); - arguments.parse(apexStarterConfigParameters); - - final ApexStarterParameterGroup parGroup = new ApexStarterParameterHandler().getParameters(arguments); - assertTrue(arguments.checkSetConfigurationFilePath()); - assertEquals(CommonTestData.APEX_STARTER_GROUP_NAME, parGroup.getName()); - } - - @Test - public void testApexStarterParameterGroup_InvalidName() throws ApexStarterException { - final String[] apexStarterConfigParameters = - { "-c", "src/test/resources/ApexStarterConfigParameters_InvalidName.json" }; - - final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); - arguments.parse(apexStarterConfigParameters); - - try { - new ApexStarterParameterHandler().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 testApexStarterVersion() throws ApexStarterException { - final String[] apexStarterConfigParameters = { "-v" }; - final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); - final String version = arguments.parse(apexStarterConfigParameters); - assertTrue(version.startsWith("ONAP Policy Framework Apex Starter Service")); - } - - @Test - public void testApexStarterHelp() throws ApexStarterException { - final String[] apexStarterConfigParameters = { "-h" }; - final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); - final String help = arguments.parse(apexStarterConfigParameters); - assertTrue(help.startsWith("usage:")); - } - - @Test - public void testApexStarterInvalidOption() throws ApexStarterException { - final String[] apexStarterConfigParameters = { "-d" }; - final ApexStarterCommandLineArguments arguments = new ApexStarterCommandLineArguments(); - try { - arguments.parse(apexStarterConfigParameters); - } catch (final Exception exp) { - assertTrue(exp.getMessage().startsWith("invalid command line arguments specified")); - } - } -} diff --git a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/TestPdpStatusParameters.java b/services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/TestPdpStatusParameters.java deleted file mode 100644 index 37cbbe021..000000000 --- a/services/services-onappf/src/test/java/org/onap/policy/apex/starter/parameters/TestPdpStatusParameters.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============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.apex.starter.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/services/services-onappf/src/test/resources/ApexStarterConfigParameters.json b/services/services-onappf/src/test/resources/ApexStarterConfigParameters.json index 6b9df6014..b1ea14de7 100644 --- a/services/services-onappf/src/test/resources/ApexStarterConfigParameters.json +++ b/services/services-onappf/src/test/resources/ApexStarterConfigParameters.json @@ -1,10 +1,9 @@ { "name":"ApexStarterParameterGroup", "pdpStatusParameters":{ - "timeIntervalMs": 2000, - "pdpName":"apex-pdp", + "timeIntervalMs": 120000, "pdpType":"apex", "description":"Pdp status for HealthCheck", - "supportedPolicyTypes":[{"name":"policy1","version":"1.0"},{"name":"policy2","version":"1.0"}] + "supportedPolicyTypes":[{"name":"onap.policies.controlloop.Operational","version":"1.0.0"}] } -} +} \ No newline at end of file diff --git a/services/services-onappf/src/test/resources/topic.properties b/services/services-onappf/src/test/resources/topic.properties index 87c6ebd54..9f3c21dff 100644 --- a/services/services-onappf/src/test/resources/topic.properties +++ b/services/services-onappf/src/test/resources/topic.properties @@ -1,3 +1,21 @@ +# ============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 -- cgit 1.2.3-korg