diff options
30 files changed, 757 insertions, 983 deletions
diff --git a/common/src/main/java/org/onap/policy/clamp/controlloop/common/handler/ControlLoopHandler.java b/common/src/main/java/org/onap/policy/clamp/controlloop/common/handler/ControlLoopHandler.java deleted file mode 100644 index 18297da42..000000000 --- a/common/src/main/java/org/onap/policy/clamp/controlloop/common/handler/ControlLoopHandler.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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.clamp.controlloop.common.handler; - -import java.util.List; -import lombok.Getter; -import lombok.NonNull; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher; -import org.onap.policy.models.provider.PolicyModelsProviderParameters; - -/** - * Abstract class for handlers for sub components in the control loop system - * - * <p>Instances are effectively singletons that are started at system start. - */ -public abstract class ControlLoopHandler { - @Getter - private final PolicyModelsProviderParameters databaseProviderParameters; - - /** - * Create a handler. - * - * @param databaseProviderParameters the parameters for access to the database - */ - protected ControlLoopHandler(@NonNull PolicyModelsProviderParameters databaseProviderParameters) { - this.databaseProviderParameters = databaseProviderParameters; - - } - - public void close() { - } - - /** - * Start any topic message listeners for this handler. - * - * @param msgDispatcher the message dispatcher with which to register the listener - */ - public void startAndRegisterListeners(MessageTypeDispatcher msgDispatcher) { - // Start and register listeners - } - - /** - * Start any topic message publishers for this handler. - * - * @param topicSinks the topic sinks on which the publisher can publish - */ - public void startAndRegisterPublishers(List<TopicSink> topicSinks) { - // Start and register publishers - } - - /** - * Stop any topic message publishers for this handler. - */ - public void stopAndUnregisterPublishers() { - // Stop and unregister publishers - } - - /** - * Stop any topic message listeners for this handler. - * - * @param msgDispatcher the message dispatcher from which to unregister the listener - */ - public void stopAndUnregisterListeners(MessageTypeDispatcher msgDispatcher) { - // Stop and unregister listeners - } - - /** - * Start any providers for this handler. - */ - public abstract void startProviders(); - - /** - * Stop any providers for this handler. - */ - public abstract void stopProviders(); -} diff --git a/common/src/test/java/org/onap/policy/clamp/controlloop/common/handler/DummyControlLoopHandler.java b/common/src/test/java/org/onap/policy/clamp/controlloop/common/handler/DummyControlLoopHandler.java deleted file mode 100644 index 1602fb6eb..000000000 --- a/common/src/test/java/org/onap/policy/clamp/controlloop/common/handler/DummyControlLoopHandler.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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.clamp.controlloop.common.handler; - -import java.util.List; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher; -import org.onap.policy.models.provider.PolicyModelsProviderParameters; - -public class DummyControlLoopHandler extends ControlLoopHandler { - - public DummyControlLoopHandler(PolicyModelsProviderParameters databaseProviderParameters) { - super(databaseProviderParameters); - } - - @Override - public void startAndRegisterListeners(MessageTypeDispatcher msgDispatcher) { - // Do nothing on this dummy class - } - - @Override - public void startAndRegisterPublishers(List<TopicSink> topicSinks) { - // Do nothing on this dummy class - } - - @Override - public void stopAndUnregisterPublishers() { - // Do nothing on this dummy class - } - - @Override - public void stopAndUnregisterListeners(MessageTypeDispatcher msgDispatcher) { - // Do nothing on this dummy class - } - - @Override - public void startProviders() { - // Do nothing on this dummy class - } - - @Override - public void stopProviders() { - // Do nothing on this dummy class - } -} diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProvider.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProvider.java index f8f1f4145..e5b062bc1 100644 --- a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProvider.java +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProvider.java @@ -33,12 +33,14 @@ import org.onap.policy.models.base.PfReferenceTimestampKey; import org.onap.policy.models.dao.PfFilterParameters; import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.models.provider.impl.AbstractModelsProvider; +import org.springframework.stereotype.Component; /** * This class provides the provision of information on control loop element statistics in the database to callers. * * @author Ramesh Murugan Iyer (ramesh.murugan.iyer@est.tech) */ +@Component public class ClElementStatisticsProvider extends AbstractModelsProvider { /** diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProvider.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProvider.java index 7c34a6654..4e502c64c 100644 --- a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProvider.java +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProvider.java @@ -40,10 +40,12 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity; import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate; import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter; import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplate; +import org.springframework.stereotype.Component; /** * This class provides information on control loop concepts in the database to callers. */ +@Component public class ControlLoopProvider extends AbstractModelsProvider { /** diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantProvider.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantProvider.java index 2ccc5d3c1..dd669a6d8 100644 --- a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantProvider.java +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantProvider.java @@ -33,10 +33,12 @@ import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.models.provider.impl.AbstractModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter; +import org.springframework.stereotype.Component; /** * This class provides information on participant concepts in the database to callers. */ +@Component public class ParticipantProvider extends AbstractModelsProvider { /** * Create a provider for participants. diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProvider.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProvider.java index 272333b88..fa27a41c2 100644 --- a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProvider.java +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProvider.java @@ -33,10 +33,12 @@ import org.onap.policy.models.base.PfTimestampKey; import org.onap.policy.models.dao.PfFilterParameters; import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.models.provider.impl.AbstractModelsProvider; +import org.springframework.stereotype.Component; /** * This class provides the provision of information on participant statistics in the database to callers. */ +@Component public class ParticipantStatisticsProvider extends AbstractModelsProvider { /** diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/Application.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/Application.java index a2b6f62d4..6b772513c 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/Application.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/Application.java @@ -22,8 +22,11 @@ package org.onap.policy.clamp.controlloop.runtime; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; @SpringBootApplication +@ComponentScan({"org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider", + "org.onap.policy.clamp.controlloop.runtime"}) public class Application { public static void main(String[] args) { diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProvider.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProvider.java index f291c4e89..bf6e39914 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProvider.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProvider.java @@ -25,8 +25,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategies; import com.fasterxml.jackson.module.jsonSchema.JsonSchema; import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper; -import java.io.Closeable; -import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -36,11 +34,8 @@ import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider; import org.onap.policy.clamp.controlloop.models.messages.rest.commissioning.CommissioningResponse; -import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.provider.PolicyModelsProvider; -import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.models.tosca.authorative.concepts.ToscaCapabilityType; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType; @@ -59,7 +54,7 @@ import org.springframework.stereotype.Component; * the callers. */ @Component -public class CommissioningProvider implements Closeable { +public class CommissioningProvider { public static final String CONTROL_LOOP_NODE_TYPE = "org.onap.policy.clamp.controlloop.ControlLoop"; private final PolicyModelsProvider modelsProvider; @@ -70,32 +65,12 @@ public class CommissioningProvider implements Closeable { /** * Create a commissioning provider. * - * @param controlLoopParameters the parameters for access to the database - * @throws PfModelRuntimeException on errors creating the database provider + * @param modelsProvider the PolicyModelsProvider + * @param clProvider the ControlLoopProvider */ - public CommissioningProvider(ClRuntimeParameterGroup controlLoopParameters) { - try { - modelsProvider = new PolicyModelsProviderFactory() - .createPolicyModelsProvider(controlLoopParameters.getDatabaseProviderParameters()); - } catch (PfModelException e) { - throw new PfModelRuntimeException(e); - } - - try { - clProvider = new ControlLoopProvider(controlLoopParameters.getDatabaseProviderParameters()); - } catch (PfModelException e) { - throw new PfModelRuntimeException(e); - } - } - - @Override - public void close() throws IOException { - try { - modelsProvider.close(); - clProvider.close(); - } catch (PfModelException e) { - throw new IOException("error closing modelsProvider", e); - } + public CommissioningProvider(PolicyModelsProvider modelsProvider, ControlLoopProvider clProvider) { + this.modelsProvider = modelsProvider; + this.clProvider = clProvider; } /** diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/ActivatorConfig.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/PolicyModelConfig.java index 1d6b92e77..8a151d886 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/ActivatorConfig.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/PolicyModelConfig.java @@ -21,26 +21,25 @@ package org.onap.policy.clamp.controlloop.runtime.config; import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; -import org.onap.policy.clamp.controlloop.runtime.main.startstop.ClRuntimeActivator; -import org.onap.policy.clamp.controlloop.runtime.supervision.SupervisionHandler; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.provider.PolicyModelsProvider; +import org.onap.policy.models.provider.PolicyModelsProviderFactory; +import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration -public class ActivatorConfig { +public class PolicyModelConfig { - /** - * Create and start ClRuntimeActivator. - * - * @param clRuntimeParameterGroup the parameters for the control loop runtime service - * @param supervisionHandler the SupervisionHandler - * @return ClRuntimeActivator - */ @Bean - public ClRuntimeActivator clRuntimeActivator(ClRuntimeParameterGroup clRuntimeParameterGroup, - SupervisionHandler supervisionHandler) { - var clRuntimeActivator = new ClRuntimeActivator(clRuntimeParameterGroup, supervisionHandler); - clRuntimeActivator.start(); - return clRuntimeActivator; + public PolicyModelsProviderParameters policyModelsProviderParameters( + ClRuntimeParameterGroup clRuntimeParameterGroup) { + return clRuntimeParameterGroup.getDatabaseProviderParameters(); + } + + @Bean + public PolicyModelsProvider policyModelsProvider(PolicyModelsProviderParameters policyModelsProviderParameters) + throws PfModelException { + return new PolicyModelsProviderFactory().createPolicyModelsProvider(policyModelsProviderParameters); } } diff --git a/common/src/test/java/org/onap/policy/clamp/controlloop/common/handler/ControlLoopHandlerTest.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/messaging/Listener.java index 7def2873a..b67ddf2a7 100644 --- a/common/src/test/java/org/onap/policy/clamp/controlloop/common/handler/ControlLoopHandlerTest.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/messaging/Listener.java @@ -18,30 +18,23 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.clamp.controlloop.common.handler; +package org.onap.policy.clamp.controlloop.runtime.config.messaging; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.onap.policy.common.endpoints.listeners.ScoListener; -import org.junit.jupiter.api.Test; -import org.onap.policy.models.provider.PolicyModelsProviderParameters; +public interface Listener { -class ControlLoopHandlerTest { + /** + * Get the type of message of interest to the listener. + * + * @return type of message of interest to the listener + */ + String getType(); - @Test - void testControlLoopHandler() { - assertThatThrownBy(() -> new DummyControlLoopHandler(null)).isInstanceOf(NullPointerException.class); - - assertNotNull(new DummyControlLoopHandler(new PolicyModelsProviderParameters())); - - PolicyModelsProviderParameters pars = new PolicyModelsProviderParameters(); - - DummyControlLoopHandler dclh = new DummyControlLoopHandler(pars); - assertNotNull(dclh); - - assertEquals(pars, dclh.getDatabaseProviderParameters()); - - dclh.close(); - } + /** + * Get listener to register. + * + * @return listener to register + */ + <T> ScoListener<T> getScoListener(); } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/main/startstop/ClRuntimeActivator.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/messaging/MessageDispatcherActivator.java index 323f76178..891dab9ae 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/main/startstop/ClRuntimeActivator.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/messaging/MessageDispatcherActivator.java @@ -18,53 +18,47 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.clamp.controlloop.runtime.main.startstop; +package org.onap.policy.clamp.controlloop.runtime.config.messaging; import java.io.Closeable; import java.io.IOException; import java.util.List; +import java.util.stream.Stream; import javax.ws.rs.core.Response.Status; import lombok.Getter; import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; -import org.onap.policy.clamp.controlloop.runtime.supervision.SupervisionHandler; import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager; 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.ServiceManagerContainer; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; -/** - * This class activates the control loop runtime component as a complete service together with all its controllers, - * listeners & handlers. - */ -public class ClRuntimeActivator extends ServiceManagerContainer implements Closeable { - // Name of the message type for messages on topics - private static final String[] MSG_TYPE_NAMES = {"messageType"}; +@Component +public class MessageDispatcherActivator extends ServiceManagerContainer implements Closeable { - @Getter - private final ClRuntimeParameterGroup parameterGroup; + private static final String[] MSG_TYPE_NAMES = {"messageType"}; // Topics from which the application receives and to which the application sends messages private List<TopicSink> topicSinks; private List<TopicSource> topicSources; - /** - * Listens for messages on the topic, decodes them into a message, and then dispatches them. - */ + @Getter private final MessageTypeDispatcher msgDispatcher; /** - * Instantiate the activator for the control loop runtime as a complete service. + * Constructor. * * @param clRuntimeParameterGroup the parameters for the control loop runtime service - * @param supervisionHandler SupervisionHandler + * @param publishers array of Publishers + * @param listeners array of Listeners * @throws ControlLoopRuntimeException if the activator does not start */ - public ClRuntimeActivator(final ClRuntimeParameterGroup clRuntimeParameterGroup, - SupervisionHandler supervisionHandler) { - this.parameterGroup = clRuntimeParameterGroup; - + public MessageDispatcherActivator(final ClRuntimeParameterGroup clRuntimeParameterGroup, Publisher[] publishers, + Listener[] listeners) { topicSinks = TopicEndpointManager.getManager() .addTopicSinks(clRuntimeParameterGroup.getTopicParameterGroup().getTopicSinks()); @@ -80,15 +74,18 @@ public class ClRuntimeActivator extends ServiceManagerContainer implements Close // @formatter:off addAction("Topic endpoint management", - () -> TopicEndpointManager.getManager().start(), - () -> TopicEndpointManager.getManager().shutdown()); + () -> TopicEndpointManager.getManager().start(), + () -> TopicEndpointManager.getManager().shutdown()); - addAction("Supervision Providers", () -> supervisionHandler.startProviders(), - () -> supervisionHandler.stopProviders()); - addAction("Supervision Listeners", () -> supervisionHandler.startAndRegisterListeners(msgDispatcher), - () -> supervisionHandler.stopAndUnregisterListeners(msgDispatcher)); - addAction("Supervision Publishers", () -> supervisionHandler.startAndRegisterPublishers(topicSinks), - () -> supervisionHandler.stopAndUnregisterPublishers()); + Stream.of(publishers).forEach(publisher -> + addAction("Publisher " + publisher.getClass().getSimpleName(), + () -> publisher.active(topicSinks), + () -> publisher.stop())); + + Stream.of(listeners).forEach(listener -> + addAction("Listener " + listener.getClass().getSimpleName(), + () -> msgDispatcher.register(listener.getType(), listener.getScoListener()), + () -> msgDispatcher.unregister(listener.getType()))); addAction("Topic Message Dispatcher", this::registerMsgDispatcher, this::unregisterMsgDispatcher); // @formatter:on @@ -112,6 +109,18 @@ public class ClRuntimeActivator extends ServiceManagerContainer implements Close } } + /** + * Start Manager after the application is Started. + * + * @param cre Refreshed Event + */ + @EventListener + public void handleContextStart(ContextRefreshedEvent cre) { + if (!isAlive()) { + start(); + } + } + @Override public void close() throws IOException { if (isAlive()) { diff --git a/common/src/main/java/org/onap/policy/clamp/controlloop/common/ControlLoopConstants.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/messaging/Publisher.java index aa8b720bc..3cd4dff85 100644 --- a/common/src/main/java/org/onap/policy/clamp/controlloop/common/ControlLoopConstants.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/config/messaging/Publisher.java @@ -1,6 +1,6 @@ -/* +/*- * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. + * Copyright (C) 2021 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,20 +13,22 @@ * 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.clamp.controlloop.common; +package org.onap.policy.clamp.controlloop.runtime.config.messaging; + +import java.util.List; +import org.onap.policy.common.endpoints.event.comm.TopicSink; /** - * Names of various items contained in the Registry. + * Publisher. */ -public class ControlLoopConstants { +public interface Publisher { - // Registry keys - public static final String REG_CLRUNTIME_ACTIVATOR = "object:activator/clruntime"; + void active(List<TopicSink> topicSinks); - private ControlLoopConstants() { - super(); - } + void stop(); } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java index c01a0b989..1011f620c 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java @@ -20,8 +20,6 @@ package org.onap.policy.clamp.controlloop.runtime.instantiation; -import java.io.Closeable; -import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -30,6 +28,7 @@ import java.util.function.UnaryOperator; import java.util.stream.Collectors; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; +import lombok.AllArgsConstructor; import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement; @@ -39,14 +38,12 @@ import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstantiationCommand; import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstantiationResponse; import org.onap.policy.clamp.controlloop.runtime.commissioning.CommissioningProvider; -import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; import org.onap.policy.clamp.controlloop.runtime.supervision.SupervisionHandler; import org.onap.policy.common.parameters.BeanValidationResult; import org.onap.policy.common.parameters.ObjectValidationResult; import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.parameters.ValidationStatus; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate; import org.springframework.stereotype.Component; @@ -55,7 +52,8 @@ import org.springframework.stereotype.Component; * This class is dedicated to the Instantiation of Commissioned control loop. */ @Component -public class ControlLoopInstantiationProvider implements Closeable { +@AllArgsConstructor +public class ControlLoopInstantiationProvider { private final ControlLoopProvider controlLoopProvider; private final CommissioningProvider commissioningProvider; private final SupervisionHandler supervisionHandler; @@ -63,30 +61,6 @@ public class ControlLoopInstantiationProvider implements Closeable { private static final Object lockit = new Object(); /** - * Create a instantiation provider. - * - * @param controlLoopParameters the parameters for access to the database - * @param commissioningProvider CommissioningProvider - * @param supervisionHandler SupervisionHandler - * @throws PfModelRuntimeException on errors creating a provider - */ - public ControlLoopInstantiationProvider(ClRuntimeParameterGroup controlLoopParameters, - CommissioningProvider commissioningProvider, SupervisionHandler supervisionHandler) { - this.commissioningProvider = commissioningProvider; - this.supervisionHandler = supervisionHandler; - try { - controlLoopProvider = new ControlLoopProvider(controlLoopParameters.getDatabaseProviderParameters()); - } catch (PfModelException e) { - throw new PfModelRuntimeException(e); - } - } - - @Override - public void close() throws IOException { - controlLoopProvider.close(); - } - - /** * Create control loops. * * @param controlLoops the control loop diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/monitoring/MonitoringProvider.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/monitoring/MonitoringProvider.java index a68505877..1f6246bd6 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/monitoring/MonitoringProvider.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/monitoring/MonitoringProvider.java @@ -20,13 +20,12 @@ package org.onap.policy.clamp.controlloop.runtime.monitoring; -import java.io.Closeable; -import java.io.IOException; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import lombok.AllArgsConstructor; import lombok.NonNull; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ClElementStatistics; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ClElementStatisticsList; @@ -36,7 +35,6 @@ import org.onap.policy.clamp.controlloop.models.controlloop.concepts.Participant import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ClElementStatisticsProvider; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ParticipantStatisticsProvider; -import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; @@ -46,7 +44,8 @@ import org.springframework.stereotype.Component; * This class provides information about statistics data of CL elements and CL Participants in database to callers. */ @Component -public class MonitoringProvider implements Closeable { +@AllArgsConstructor +public class MonitoringProvider { private static final String DESC_ORDER = "DESC"; private final ParticipantStatisticsProvider participantStatisticsProvider; @@ -54,32 +53,6 @@ public class MonitoringProvider implements Closeable { private final ControlLoopProvider controlLoopProvider; /** - * Create a Monitoring provider. - * - * @param controlLoopParameters the parameters for access to the database - * @throws PfModelRuntimeException on errors creating the provider - */ - public MonitoringProvider(ClRuntimeParameterGroup controlLoopParameters) { - - try { - participantStatisticsProvider = - new ParticipantStatisticsProvider(controlLoopParameters.getDatabaseProviderParameters()); - clElementStatisticsProvider = - new ClElementStatisticsProvider(controlLoopParameters.getDatabaseProviderParameters()); - controlLoopProvider = new ControlLoopProvider(controlLoopParameters.getDatabaseProviderParameters()); - } catch (PfModelException e) { - throw new PfModelRuntimeException(e); - } - } - - @Override - public void close() throws IOException { - controlLoopProvider.close(); - clElementStatisticsProvider.close(); - participantStatisticsProvider.close(); - } - - /** * Create participant statistics. * * @param participantStatistics the participant statistics diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandler.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandler.java index e1b4be48b..aba545750 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandler.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandler.java @@ -21,34 +21,20 @@ package org.onap.policy.clamp.controlloop.runtime.supervision; import java.util.List; -import java.util.UUID; import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; +import lombok.AllArgsConstructor; import org.apache.commons.collections4.CollectionUtils; import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException; -import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; -import org.onap.policy.clamp.controlloop.common.handler.ControlLoopHandler; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.Participant; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ParticipantProvider; -import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantControlLoopStateChange; -import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantControlLoopUpdate; -import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantMessageType; import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantStatus; -import org.onap.policy.clamp.controlloop.runtime.commissioning.CommissioningProvider; -import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; import org.onap.policy.clamp.controlloop.runtime.monitoring.MonitoringProvider; import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantControlLoopStateChangePublisher; import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantControlLoopUpdatePublisher; -import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantStateChangePublisher; -import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantStatusListener; -import org.onap.policy.common.endpoints.event.comm.TopicSink; -import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher; -import org.onap.policy.common.utils.services.ServiceManager; -import org.onap.policy.common.utils.services.ServiceManagerException; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.slf4j.Logger; @@ -58,10 +44,12 @@ import org.springframework.stereotype.Component; /** * This class handles supervision of control loop instances, so only one object of this type should be built at a time. * - * <p/> It is effectively a singleton that is started at system start. + * <p/> + * It is effectively a singleton that is started at system start. */ @Component -public class SupervisionHandler extends ControlLoopHandler { +@AllArgsConstructor +public class SupervisionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(SupervisionHandler.class); private static final String CONTROL_LOOP_CANNOT_TRANSITION_FROM_STATE = "Control loop can't transition from state "; @@ -69,59 +57,13 @@ public class SupervisionHandler extends ControlLoopHandler { private static final String TO_STATE = " to state "; private static final String AND_TRANSITIONING_TO_STATE = " and transitioning to state "; - private ControlLoopProvider controlLoopProvider; - private ParticipantProvider participantProvider; + private final ControlLoopProvider controlLoopProvider; + private final ParticipantProvider participantProvider; private final MonitoringProvider monitoringProvider; - private final CommissioningProvider commissioningProvider; // Publishers for participant communication - private ParticipantStateChangePublisher stateChangePublisher; - private ParticipantControlLoopUpdatePublisher controlLoopUpdatePublisher; - private ParticipantControlLoopStateChangePublisher controlLoopStateChangePublisher; - - private long supervisionScannerIntervalSec; - private long participantStateChangeIntervalSec; - private long participantClUpdateIntervalSec; - private long participantClStateChangeIntervalSec; - - // Database scanner - private SupervisionScanner scanner; - - /** - * Used to manage the services. - */ - private ServiceManager manager; - private ServiceManager publisherManager; - - /** - * Create a handler. - * - * @param clRuntimeParameterGroup the parameters for the control loop runtime - * @param monitoringProvider the MonitoringProvider - * @param commissioningProvider the CommissioningProvider - */ - public SupervisionHandler(ClRuntimeParameterGroup clRuntimeParameterGroup, MonitoringProvider monitoringProvider, - CommissioningProvider commissioningProvider) { - super(clRuntimeParameterGroup.getDatabaseProviderParameters()); - this.monitoringProvider = monitoringProvider; - this.commissioningProvider = commissioningProvider; - - // @formatter:off - this.manager = new ServiceManager() - .addAction("ControlLoop Provider", - () -> controlLoopProvider = new ControlLoopProvider(getDatabaseProviderParameters()), - () -> controlLoopProvider = null) - .addAction("Participant Provider", - () -> participantProvider = new ParticipantProvider(getDatabaseProviderParameters()), - () -> participantProvider = null); - // @formatter:on - - supervisionScannerIntervalSec = clRuntimeParameterGroup.getSupervisionScannerIntervalSec(); - participantStateChangeIntervalSec = clRuntimeParameterGroup.getParticipantClStateChangeIntervalSec(); - participantClUpdateIntervalSec = clRuntimeParameterGroup.getParticipantClUpdateIntervalSec(); - participantClStateChangeIntervalSec = clRuntimeParameterGroup.getParticipantClStateChangeIntervalSec(); - - } + private final ParticipantControlLoopUpdatePublisher controlLoopUpdatePublisher; + private final ParticipantControlLoopStateChangePublisher controlLoopStateChangePublisher; /** * Supervision trigger called when a command is issued on control loops. @@ -155,55 +97,6 @@ public class SupervisionHandler extends ControlLoopHandler { } } - @Override - public void startAndRegisterListeners(MessageTypeDispatcher msgDispatcher) { - msgDispatcher.register(ParticipantMessageType.PARTICIPANT_STATUS.name(), new ParticipantStatusListener(this)); - } - - @Override - public void startAndRegisterPublishers(List<TopicSink> topicSinks) { - // @formatter:off - this.publisherManager = new ServiceManager() - .addAction("Supervision scanner", - () -> scanner = - new SupervisionScanner(controlLoopProvider, supervisionScannerIntervalSec), - () -> scanner.close()) - .addAction("ControlLoopUpdate publisher", - () -> controlLoopUpdatePublisher = - new ParticipantControlLoopUpdatePublisher(topicSinks, participantClUpdateIntervalSec), - () -> controlLoopUpdatePublisher.terminate()) - .addAction("StateChange Publisher", - () -> stateChangePublisher = - new ParticipantStateChangePublisher(topicSinks, participantStateChangeIntervalSec), - () -> stateChangePublisher.terminate()) - .addAction("ControlLoopStateChange Publisher", - () -> controlLoopStateChangePublisher = - new ParticipantControlLoopStateChangePublisher(topicSinks, participantClStateChangeIntervalSec), - () -> controlLoopStateChangePublisher.terminate()); - // @formatter:on - try { - publisherManager.start(); - } catch (final ServiceManagerException exp) { - throw new ControlLoopRuntimeException(Status.INTERNAL_SERVER_ERROR, - "Supervision handler start of publishers or scanner failed", exp); - } - } - - @Override - public void stopAndUnregisterPublishers() { - try { - publisherManager.stop(); - } catch (final ServiceManagerException exp) { - throw new ControlLoopRuntimeException(Status.INTERNAL_SERVER_ERROR, - "Supervision handler stop of publishers or scanner failed", exp); - } - } - - @Override - public void stopAndUnregisterListeners(MessageTypeDispatcher msgDispatcher) { - msgDispatcher.unregister(ParticipantMessageType.PARTICIPANT_STATUS.name()); - } - /** * Handle a ParticipantStatus message from a participant. * @@ -270,7 +163,7 @@ public class SupervisionHandler extends ControlLoopHandler { case UNINITIALISED2PASSIVE: case PASSIVE: controlLoop.setState(ControlLoopState.PASSIVE2UNINITIALISED); - sendControlLoopStateChange(controlLoop); + controlLoopStateChangePublisher.send(controlLoop); break; case PASSIVE2UNINITIALISED: @@ -294,7 +187,7 @@ public class SupervisionHandler extends ControlLoopHandler { break; case UNINITIALISED: controlLoop.setState(ControlLoopState.UNINITIALISED2PASSIVE); - sendControlLoopUpdate(controlLoop); + controlLoopUpdatePublisher.send(controlLoop); break; case UNINITIALISED2PASSIVE: @@ -305,7 +198,7 @@ public class SupervisionHandler extends ControlLoopHandler { case RUNNING: controlLoop.setState(ControlLoopState.RUNNING2PASSIVE); - sendControlLoopStateChange(controlLoop); + controlLoopStateChangePublisher.send(controlLoop); break; default: @@ -329,7 +222,7 @@ public class SupervisionHandler extends ControlLoopHandler { case PASSIVE: controlLoop.setState(ControlLoopState.PASSIVE2RUNNING); - sendControlLoopStateChange(controlLoop); + controlLoopStateChangePublisher.send(controlLoop); break; default: @@ -339,25 +232,6 @@ public class SupervisionHandler extends ControlLoopHandler { } } - private void sendControlLoopUpdate(ControlLoop controlLoop) throws PfModelException { - var pclu = new ParticipantControlLoopUpdate(); - pclu.setControlLoopId(controlLoop.getKey().asIdentifier()); - pclu.setControlLoop(controlLoop); - // TODO: We should look up the correct TOSCA node template here for the control loop - // Tiny hack implemented to return the tosca service template entry from the database and be passed onto dmaap - pclu.setControlLoopDefinition(commissioningProvider.getToscaServiceTemplate(null, null)); - controlLoopUpdatePublisher.send(pclu); - } - - private void sendControlLoopStateChange(ControlLoop controlLoop) { - var clsc = new ParticipantControlLoopStateChange(); - clsc.setControlLoopId(controlLoop.getKey().asIdentifier()); - clsc.setMessageId(UUID.randomUUID()); - clsc.setOrderedState(controlLoop.getOrderedState()); - - controlLoopStateChangePublisher.send(clsc); - } - private void superviseParticipant(ParticipantStatus participantStatusMessage) throws PfModelException, ControlLoopException { if (participantStatusMessage.getParticipantId() == null) { @@ -427,26 +301,6 @@ public class SupervisionHandler extends ControlLoopHandler { } } - @Override - public void startProviders() { - try { - manager.start(); - } catch (final ServiceManagerException exp) { - throw new ControlLoopRuntimeException(Status.INTERNAL_SERVER_ERROR, - "Supervision handler start of providers failed", exp); - } - } - - @Override - public void stopProviders() { - try { - manager.stop(); - } catch (final ServiceManagerException exp) { - throw new ControlLoopRuntimeException(Status.INTERNAL_SERVER_ERROR, - "Supervision handler stop of providers failed", exp); - } - } - private void exceptionOccured(Response.Status status, String reason) throws ControlLoopException { throw new ControlLoopException(status, reason); } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScanner.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScanner.java index 4f3faf8af..68f5830c0 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScanner.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScanner.java @@ -27,13 +27,16 @@ import java.util.concurrent.TimeUnit; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider; +import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; import org.onap.policy.models.base.PfModelException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; /** * This class is used to scan the control loops in the database and check if they are in the correct state. */ +@Component public class SupervisionScanner implements Runnable, Closeable { private static final Logger LOGGER = LoggerFactory.getLogger(SupervisionScanner.class); @@ -43,15 +46,17 @@ public class SupervisionScanner implements Runnable, Closeable { /** * Constructor for instantiating SupervisionScanner. * + * @param clRuntimeParameterGroup the parameters for the control loop runtime * @param controlLoopProvider the provider to use to read control loops from the database - * @param interval time interval to perform scans */ - public SupervisionScanner(final ControlLoopProvider controlLoopProvider, final long interval) { + public SupervisionScanner(final ControlLoopProvider controlLoopProvider, + ClRuntimeParameterGroup clRuntimeParameterGroup) { this.controlLoopProvider = controlLoopProvider; // Kick off the timer timerPool = makeTimerPool(); - timerPool.scheduleAtFixedRate(this, 0, interval, TimeUnit.SECONDS); + timerPool.scheduleAtFixedRate(this, 0, clRuntimeParameterGroup.getSupervisionScannerIntervalSec(), + TimeUnit.SECONDS); } @Override diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/AbstractParticipantPublisher.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/AbstractParticipantPublisher.java index c54856101..3c87b05b4 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/AbstractParticipantPublisher.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/AbstractParticipantPublisher.java @@ -21,35 +21,17 @@ package org.onap.policy.clamp.controlloop.runtime.supervision.comm; import java.util.List; -import lombok.Getter; +import javax.ws.rs.core.Response.Status; +import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeException; import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantMessage; +import org.onap.policy.clamp.controlloop.runtime.config.messaging.Publisher; import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.common.endpoints.event.comm.client.TopicSinkClient; -public abstract class AbstractParticipantPublisher<E extends ParticipantMessage> { +public abstract class AbstractParticipantPublisher<E extends ParticipantMessage> implements Publisher { - private final TopicSinkClient topicSinkClient; - - @Getter - private final long intervalSec; - - /** - * Constructor. - * - * @param topicSinks the topic sinks - * @param intervalSec time interval to send ParticipantStateChange messages - */ - protected AbstractParticipantPublisher(final List<TopicSink> topicSinks, long intervalSec) { - this.topicSinkClient = new TopicSinkClient(topicSinks.get(0)); - this.intervalSec = intervalSec; - } - - /** - * Terminates the current timer. - */ - public void terminate() { - // Nothing to terminate, this publisher does not have a timer - } + private TopicSinkClient topicSinkClient; + private boolean active = false; /** * Method to send Participant message to participants on demand. @@ -57,6 +39,24 @@ public abstract class AbstractParticipantPublisher<E extends ParticipantMessage> * @param participantMessage the Participant message */ public void send(final E participantMessage) { + if (!active) { + throw new ControlLoopRuntimeException(Status.NOT_ACCEPTABLE, "Not Active!"); + } topicSinkClient.send(participantMessage); } + + + @Override + public void active(List<TopicSink> topicSinks) { + if (topicSinks.size() != 1) { + throw new IllegalArgumentException("Topic Sink must be one"); + } + this.topicSinkClient = new TopicSinkClient(topicSinks.get(0)); + active = true; + } + + @Override + public void stop() { + active = false; + } } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantControlLoopStateChangePublisher.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantControlLoopStateChangePublisher.java index c9d0a4fe4..734ccb842 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantControlLoopStateChangePublisher.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantControlLoopStateChangePublisher.java @@ -20,23 +20,29 @@ package org.onap.policy.clamp.controlloop.runtime.supervision.comm; -import java.util.List; +import java.util.UUID; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantControlLoopStateChange; -import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.springframework.stereotype.Component; /** * This class is used to send ParticipantControlLoopStateChangePublisher messages to participants on DMaaP. */ +@Component public class ParticipantControlLoopStateChangePublisher extends AbstractParticipantPublisher<ParticipantControlLoopStateChange> { /** - * Constructor for instantiating ParticipantControlLoopStateChangePublisherPublisher. + * Send ControlLoopStateChange to Participant. * - * @param topicSinks the topic sinks - * @param interval time interval to send ParticipantControlLoopStateChangePublisher messages + * @param controlLoop the ControlLoop */ - public ParticipantControlLoopStateChangePublisher(final List<TopicSink> topicSinks, final long interval) { - super(topicSinks, interval); + public void send(ControlLoop controlLoop) { + var clsc = new ParticipantControlLoopStateChange(); + clsc.setControlLoopId(controlLoop.getKey().asIdentifier()); + clsc.setMessageId(UUID.randomUUID()); + clsc.setOrderedState(controlLoop.getOrderedState()); + + super.send(clsc); } } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantControlLoopUpdatePublisher.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantControlLoopUpdatePublisher.java index fbbd95fbc..8d40c5e69 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantControlLoopUpdatePublisher.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantControlLoopUpdatePublisher.java @@ -20,22 +20,42 @@ package org.onap.policy.clamp.controlloop.runtime.supervision.comm; -import java.util.List; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantControlLoopUpdate; -import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.onap.policy.clamp.controlloop.runtime.commissioning.CommissioningProvider; +import org.onap.policy.models.base.PfModelException; +import org.springframework.stereotype.Component; /** * This class is used to send ParticipantControlLoopUpdate messages to participants on DMaaP. */ +@Component public class ParticipantControlLoopUpdatePublisher extends AbstractParticipantPublisher<ParticipantControlLoopUpdate> { + private final CommissioningProvider commissioningProvider; + + /** + * Constructor. + * + * @param commissioningProvider the CommissioningProvider + */ + public ParticipantControlLoopUpdatePublisher(CommissioningProvider commissioningProvider) { + this.commissioningProvider = commissioningProvider; + } + /** - * Constructor for instantiating ParticipantUpdatePublisher. + * Send ControlLoopUpdate to Participant. * - * @param topicSinks the topic sinks - * @param interval time interval to send ParticipantControlLoopUpdate messages + * @param controlLoop the ControlLoop + * @throws PfModelException on errors getting the Control Loop Definition */ - public ParticipantControlLoopUpdatePublisher(final List<TopicSink> topicSinks, final long interval) { - super(topicSinks, interval); + public void send(ControlLoop controlLoop) throws PfModelException { + var pclu = new ParticipantControlLoopUpdate(); + pclu.setControlLoopId(controlLoop.getKey().asIdentifier()); + pclu.setControlLoop(controlLoop); + // TODO: We should look up the correct TOSCA node template here for the control loop + // Tiny hack implemented to return the tosca service template entry from the database and be passed onto dmaap + pclu.setControlLoopDefinition(commissioningProvider.getToscaServiceTemplate(null, null)); + super.send(pclu); } } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantStateChangePublisher.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantStateChangePublisher.java index 20cdea6f4..b63cbdf03 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantStateChangePublisher.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantStateChangePublisher.java @@ -20,22 +20,13 @@ package org.onap.policy.clamp.controlloop.runtime.supervision.comm; -import java.util.List; import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantStateChange; -import org.onap.policy.common.endpoints.event.comm.TopicSink; +import org.springframework.stereotype.Component; /** * This class is used to send ParticipantStateChange messages to participants on DMaaP. */ +@Component public class ParticipantStateChangePublisher extends AbstractParticipantPublisher<ParticipantStateChange> { - /** - * Constructor for instantiating ParticipantStateChangePublisher. - * - * @param topicSinks the topic sinks - * @param interval time interval to send ParticipantStateChange messages - */ - public ParticipantStateChangePublisher(List<TopicSink> topicSinks, long interval) { - super(topicSinks, interval); - } } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantStatusListener.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantStatusListener.java index 88b838613..8fa076240 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantStatusListener.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/ParticipantStatusListener.java @@ -20,18 +20,22 @@ package org.onap.policy.clamp.controlloop.runtime.supervision.comm; +import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantMessageType; import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantStatus; +import org.onap.policy.clamp.controlloop.runtime.config.messaging.Listener; import org.onap.policy.clamp.controlloop.runtime.supervision.SupervisionHandler; 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.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; /** * Listener for ParticipantStatus messages sent by participants. */ -public class ParticipantStatusListener extends ScoListener<ParticipantStatus> { +@Component +public class ParticipantStatusListener extends ScoListener<ParticipantStatus> implements Listener { private static final Logger LOGGER = LoggerFactory.getLogger(ParticipantStatusListener.class); private final SupervisionHandler supervisionHandler; @@ -50,4 +54,14 @@ public class ParticipantStatusListener extends ScoListener<ParticipantStatus> { LOGGER.debug("ParticipantStatus message received from participant - {}", participantStatusMessage); supervisionHandler.handleParticipantStatusMessage(participantStatusMessage); } + + @Override + public String getType() { + return ParticipantMessageType.PARTICIPANT_STATUS.name(); + } + + @Override + public ScoListener<ParticipantStatus> getScoListener() { + return this; + } } diff --git a/runtime-controlloop/src/main/resources/parameters/ClRuntimeParameters.json b/runtime-controlloop/src/main/resources/parameters/ClRuntimeParameters.json index a6c19837e..00ca7f9a6 100644 --- a/runtime-controlloop/src/main/resources/parameters/ClRuntimeParameters.json +++ b/runtime-controlloop/src/main/resources/parameters/ClRuntimeParameters.json @@ -50,13 +50,6 @@ "message-router" ], "topicCommInfrastructure": "dmaap" - }, - { - "topic": "POLICY-NOTIFICATION", - "servers": [ - "message-router" - ], - "topicCommInfrastructure": "dmaap" } ] } diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProviderTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProviderTest.java index fdddcf996..440380781 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProviderTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProviderTest.java @@ -26,13 +26,17 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider; import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; +import org.onap.policy.clamp.controlloop.runtime.util.CommonTestData; import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.coder.YamlJsonTranslator; import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate; import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeType; @@ -47,6 +51,9 @@ class CommissioningProviderTest { private static int dbNum = 0; private static final Object lockit = new Object(); + private PolicyModelsProvider modelsProvider = null; + private ControlLoopProvider clProvider = null; + private static String getParameterGroupAsString() { dbNum++; return ResourceUtils.getResourceAsString("src/test/resources/parameters/TestParameters.json") @@ -64,6 +71,16 @@ class CommissioningProviderTest { } } + @AfterEach + void close() throws Exception { + if (modelsProvider != null) { + modelsProvider.close(); + } + if (clProvider != null) { + clProvider.close(); + } + } + /** * Test the fetching of control loop definitions (ToscaServiceTemplates). * @@ -71,33 +88,34 @@ class CommissioningProviderTest { */ @Test void testGetControlLoopDefinitions() throws Exception { - List<ToscaNodeTemplate> listOfTemplates; ClRuntimeParameterGroup clRuntimeParameterGroup = getClRuntimeParameterGroup(); + modelsProvider = + CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + + CommissioningProvider provider = new CommissioningProvider(modelsProvider, clProvider); + ToscaServiceTemplate serviceTemplate = yamlTranslator + .fromYaml(ResourceUtils.getResourceAsString(TOSCA_SERVICE_TEMPLATE_YAML), ToscaServiceTemplate.class); + + List<ToscaNodeTemplate> listOfTemplates = provider.getControlLoopDefinitions(null, null); + assertThat(listOfTemplates).isEmpty(); + + provider.createControlLoopDefinitions(serviceTemplate); + listOfTemplates = provider.getControlLoopDefinitions(null, null); + assertThat(listOfTemplates).hasSize(2); + + // Test Filtering + listOfTemplates = provider.getControlLoopDefinitions("org.onap.domain.pmsh.PMSHControlLoopDefinition", "1.2.3"); + assertThat(listOfTemplates).hasSize(1); + for (ToscaNodeTemplate template : listOfTemplates) { + // Other CL elements contain PMSD instead of PMSH in their name + assertThat(template.getName()).doesNotContain("PMSD"); + } - try (var provider = new CommissioningProvider(clRuntimeParameterGroup)) { - ToscaServiceTemplate serviceTemplate = yamlTranslator.fromYaml( - ResourceUtils.getResourceAsString(TOSCA_SERVICE_TEMPLATE_YAML), ToscaServiceTemplate.class); - - listOfTemplates = provider.getControlLoopDefinitions(null, null); - assertThat(listOfTemplates).isEmpty(); - - provider.createControlLoopDefinitions(serviceTemplate); - listOfTemplates = provider.getControlLoopDefinitions(null, null); - assertThat(listOfTemplates).hasSize(2); - - // Test Filtering - listOfTemplates = - provider.getControlLoopDefinitions("org.onap.domain.pmsh.PMSHControlLoopDefinition", "1.2.3"); - assertThat(listOfTemplates).hasSize(1); - for (ToscaNodeTemplate template : listOfTemplates) { - // Other CL elements contain PMSD instead of PMSH in their name - assertThat(template.getName()).doesNotContain("PMSD"); - } + // Test Wrong Name + listOfTemplates = provider.getControlLoopDefinitions("WrongControlLoopName", "0.0.0"); + assertThat(listOfTemplates).isEmpty(); - // Test Wrong Name - listOfTemplates = provider.getControlLoopDefinitions("WrongControlLoopName", "0.0.0"); - assertThat(listOfTemplates).isEmpty(); - } } /** @@ -107,25 +125,26 @@ class CommissioningProviderTest { */ @Test void testCreateControlLoopDefinitions() throws Exception { - List<ToscaNodeTemplate> listOfTemplates; ClRuntimeParameterGroup clRuntimeParameterGroup = getClRuntimeParameterGroup(); - - try (var provider = new CommissioningProvider(clRuntimeParameterGroup)) { - // Test Service template is null - assertThatThrownBy(() -> provider.createControlLoopDefinitions(null)).hasMessageMatching(TEMPLATE_IS_NULL); - listOfTemplates = provider.getControlLoopDefinitions(null, null); - assertThat(listOfTemplates).isEmpty(); - - ToscaServiceTemplate serviceTemplate = yamlTranslator.fromYaml( - ResourceUtils.getResourceAsString(TOSCA_SERVICE_TEMPLATE_YAML), ToscaServiceTemplate.class); - - // Response should return the number of node templates present in the service template - List<ToscaConceptIdentifier> affectedDefinitions = - provider.createControlLoopDefinitions(serviceTemplate).getAffectedControlLoopDefinitions(); - assertThat(affectedDefinitions).hasSize(13); - listOfTemplates = provider.getControlLoopDefinitions(null, null); - assertThat(listOfTemplates).hasSize(2); - } + modelsProvider = + CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + + CommissioningProvider provider = new CommissioningProvider(modelsProvider, clProvider); + // Test Service template is null + assertThatThrownBy(() -> provider.createControlLoopDefinitions(null)).hasMessageMatching(TEMPLATE_IS_NULL); + List<ToscaNodeTemplate> listOfTemplates = provider.getControlLoopDefinitions(null, null); + assertThat(listOfTemplates).isEmpty(); + + ToscaServiceTemplate serviceTemplate = yamlTranslator + .fromYaml(ResourceUtils.getResourceAsString(TOSCA_SERVICE_TEMPLATE_YAML), ToscaServiceTemplate.class); + + // Response should return the number of node templates present in the service template + List<ToscaConceptIdentifier> affectedDefinitions = + provider.createControlLoopDefinitions(serviceTemplate).getAffectedControlLoopDefinitions(); + assertThat(affectedDefinitions).hasSize(13); + listOfTemplates = provider.getControlLoopDefinitions(null, null); + assertThat(listOfTemplates).hasSize(2); } /** @@ -135,24 +154,25 @@ class CommissioningProviderTest { */ @Test void testDeleteControlLoopDefinitions() throws Exception { - List<ToscaNodeTemplate> listOfTemplates; ClRuntimeParameterGroup clRuntimeParameterGroup = getClRuntimeParameterGroup(); + modelsProvider = + CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - try (var provider = new CommissioningProvider(clRuntimeParameterGroup)) { - ToscaServiceTemplate serviceTemplate = yamlTranslator.fromYaml( - ResourceUtils.getResourceAsString(TOSCA_SERVICE_TEMPLATE_YAML), ToscaServiceTemplate.class); + CommissioningProvider provider = new CommissioningProvider(modelsProvider, clProvider); + ToscaServiceTemplate serviceTemplate = yamlTranslator + .fromYaml(ResourceUtils.getResourceAsString(TOSCA_SERVICE_TEMPLATE_YAML), ToscaServiceTemplate.class); - listOfTemplates = provider.getControlLoopDefinitions(null, null); - assertThat(listOfTemplates).isEmpty(); + List<ToscaNodeTemplate> listOfTemplates = provider.getControlLoopDefinitions(null, null); + assertThat(listOfTemplates).isEmpty(); - provider.createControlLoopDefinitions(serviceTemplate); - listOfTemplates = provider.getControlLoopDefinitions(null, null); - assertThat(listOfTemplates).hasSize(2); + provider.createControlLoopDefinitions(serviceTemplate); + listOfTemplates = provider.getControlLoopDefinitions(null, null); + assertThat(listOfTemplates).hasSize(2); - provider.deleteControlLoopDefinition(serviceTemplate.getName(), serviceTemplate.getVersion()); - listOfTemplates = provider.getControlLoopDefinitions(null, null); - assertThat(listOfTemplates).isEmpty(); - } + provider.deleteControlLoopDefinition(serviceTemplate.getName(), serviceTemplate.getVersion()); + listOfTemplates = provider.getControlLoopDefinitions(null, null); + assertThat(listOfTemplates).isEmpty(); } /** @@ -163,26 +183,29 @@ class CommissioningProviderTest { @Test void testGetControlLoopElementDefinitions() throws Exception { ClRuntimeParameterGroup clRuntimeParameterGroup = getClRuntimeParameterGroup(); - try (var provider = new CommissioningProvider(clRuntimeParameterGroup)) { - ToscaServiceTemplate serviceTemplate = yamlTranslator.fromYaml( - ResourceUtils.getResourceAsString(TOSCA_SERVICE_TEMPLATE_YAML), ToscaServiceTemplate.class); + modelsProvider = + CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - provider.getControlLoopDefinitions(null, null); + CommissioningProvider provider = new CommissioningProvider(modelsProvider, clProvider); + ToscaServiceTemplate serviceTemplate = yamlTranslator + .fromYaml(ResourceUtils.getResourceAsString(TOSCA_SERVICE_TEMPLATE_YAML), ToscaServiceTemplate.class); - provider.createControlLoopDefinitions(serviceTemplate); - List<ToscaNodeTemplate> controlLoopDefinitionList = - provider.getControlLoopDefinitions("org.onap.domain.pmsh.PMSHControlLoopDefinition", "1.2.3"); + provider.getControlLoopDefinitions(null, null); - List<ToscaNodeTemplate> controlLoopElementNodeTemplates = - provider.getControlLoopElementDefinitions(controlLoopDefinitionList.get(0)); + provider.createControlLoopDefinitions(serviceTemplate); + List<ToscaNodeTemplate> controlLoopDefinitionList = + provider.getControlLoopDefinitions("org.onap.domain.pmsh.PMSHControlLoopDefinition", "1.2.3"); - // 4 PMSH control loop elements definitions. - assertThat(controlLoopElementNodeTemplates).hasSize(4); + List<ToscaNodeTemplate> controlLoopElementNodeTemplates = + provider.getControlLoopElementDefinitions(controlLoopDefinitionList.get(0)); - List<ToscaNodeType> derivedTypes = getDerivedNodeTypes(serviceTemplate); - for (ToscaNodeTemplate template : controlLoopElementNodeTemplates) { - assertTrue(checkNodeType(template, derivedTypes)); - } + // 4 PMSH control loop elements definitions. + assertThat(controlLoopElementNodeTemplates).hasSize(4); + + List<ToscaNodeType> derivedTypes = getDerivedNodeTypes(serviceTemplate); + for (ToscaNodeTemplate template : controlLoopElementNodeTemplates) { + assertTrue(checkNodeType(template, derivedTypes)); } } diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/config/messaging/MessageDispatcherActivatorTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/config/messaging/MessageDispatcherActivatorTest.java new file mode 100644 index 000000000..2b4abaa3b --- /dev/null +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/config/messaging/MessageDispatcherActivatorTest.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2021 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * 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.clamp.controlloop.runtime.config.messaging; + +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; +import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterHandler; +import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantStatusListener; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.coder.StandardCoderObject; + +/** + * Class to perform unit test of {@link MessageDispatcherActivator}}. + * + */ +class MessageDispatcherActivatorTest { + + private static final Coder CODER = new StandardCoder(); + + private static final String TOPIC_FIRST = "TOPIC1"; + private static final String TOPIC_SECOND = "TOPIC2"; + + @Test + void testStartAndStop() throws Exception { + final String path = "src/test/resources/parameters/TestParameters.json"; + ClRuntimeParameterGroup parameterGroup = new ClRuntimeParameterHandler().getParameters(path); + + var publisherFirst = spy(mock(Publisher.class)); + var publisherSecond = spy(mock(Publisher.class)); + var publishers = new Publisher[] {publisherFirst, publisherSecond}; + + var listenerFirst = spy(mock(ParticipantStatusListener.class)); + when(listenerFirst.getType()).thenReturn(TOPIC_FIRST); + when(listenerFirst.getScoListener()).thenReturn(listenerFirst); + + var listenerSecond = spy(mock(ParticipantStatusListener.class)); + when(listenerSecond.getType()).thenReturn(TOPIC_SECOND); + when(listenerSecond.getScoListener()).thenReturn(listenerSecond); + + var listeners = new Listener[] {listenerFirst, listenerSecond}; + + try (var activator = new MessageDispatcherActivator(parameterGroup, publishers, listeners)) { + + assertFalse(activator.isAlive()); + activator.start(); + assertTrue(activator.isAlive()); + + // repeat start - should throw an exception + assertThatIllegalStateException().isThrownBy(() -> activator.start()); + assertTrue(activator.isAlive()); + verify(publisherFirst, times(1)).active(anyList()); + verify(publisherSecond, times(1)).active(anyList()); + + StandardCoderObject sco = CODER.decode("{messageType:" + TOPIC_FIRST + "}", StandardCoderObject.class); + activator.getMsgDispatcher().onTopicEvent(null, "msg", sco); + verify(listenerFirst, times(1)).onTopicEvent(any(), any(), any()); + + sco = CODER.decode("{messageType:" + TOPIC_SECOND + "}", StandardCoderObject.class); + activator.getMsgDispatcher().onTopicEvent(null, "msg", sco); + verify(listenerSecond, times(1)).onTopicEvent(any(), any(), any()); + + activator.stop(); + assertFalse(activator.isAlive()); + + // repeat stop - should throw an exception + assertThatIllegalStateException().isThrownBy(() -> activator.stop()); + assertFalse(activator.isAlive()); + } + } +} diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java index b93bd0f0e..1d7a00b18 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java @@ -25,7 +25,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.IOException; import java.util.ArrayList; -import java.util.Collections; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -33,15 +33,21 @@ import org.onap.policy.clamp.controlloop.common.exception.ControlLoopRuntimeExce import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoops; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ClElementStatisticsProvider; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ParticipantProvider; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ParticipantStatisticsProvider; import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstantiationCommand; import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstantiationResponse; import org.onap.policy.clamp.controlloop.runtime.commissioning.CommissioningProvider; import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; import org.onap.policy.clamp.controlloop.runtime.monitoring.MonitoringProvider; import org.onap.policy.clamp.controlloop.runtime.supervision.SupervisionHandler; +import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantControlLoopStateChangePublisher; +import org.onap.policy.clamp.controlloop.runtime.supervision.comm.ParticipantControlLoopUpdatePublisher; import org.onap.policy.clamp.controlloop.runtime.util.CommonTestData; -import org.onap.policy.common.endpoints.event.comm.TopicSink; import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; /** @@ -79,9 +85,10 @@ class ControlLoopInstantiationProviderTest { + " item \"ControlLoop\" value \"org.onap.domain.PMSHControlLoopDefinition\" INVALID," + " Commissioned control loop definition not FOUND\n"; - private static ClRuntimeParameterGroup controlLoopParameters; private static SupervisionHandler supervisionHandler; private static CommissioningProvider commissioningProvider; + private static ControlLoopProvider clProvider; + private static PolicyModelsProvider modelsProvider; /** * setup Db Provider Parameters. @@ -90,12 +97,29 @@ class ControlLoopInstantiationProviderTest { */ @BeforeAll public static void setupDbProviderParameters() throws PfModelException { - controlLoopParameters = CommonTestData.geParameterGroup(0, "instantproviderdb"); - commissioningProvider = new CommissioningProvider(controlLoopParameters); - var monitoringProvider = new MonitoringProvider(controlLoopParameters); - supervisionHandler = new SupervisionHandler(controlLoopParameters, monitoringProvider, commissioningProvider); - supervisionHandler.startProviders(); - supervisionHandler.startAndRegisterPublishers(Collections.singletonList(Mockito.mock(TopicSink.class))); + ClRuntimeParameterGroup controlLoopParameters = CommonTestData.geParameterGroup(0, "instantproviderdb"); + + modelsProvider = + CommonTestData.getPolicyModelsProvider(controlLoopParameters.getDatabaseProviderParameters()); + clProvider = new ControlLoopProvider(controlLoopParameters.getDatabaseProviderParameters()); + var participantStatisticsProvider = + new ParticipantStatisticsProvider(controlLoopParameters.getDatabaseProviderParameters()); + var clElementStatisticsProvider = + new ClElementStatisticsProvider(controlLoopParameters.getDatabaseProviderParameters()); + commissioningProvider = new CommissioningProvider(modelsProvider, clProvider); + var monitoringProvider = + new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider); + var participantProvider = new ParticipantProvider(controlLoopParameters.getDatabaseProviderParameters()); + var controlLoopUpdatePublisher = Mockito.mock(ParticipantControlLoopUpdatePublisher.class); + var controlLoopStateChangePublisher = Mockito.mock(ParticipantControlLoopStateChangePublisher.class); + supervisionHandler = new SupervisionHandler(clProvider, participantProvider, monitoringProvider, + controlLoopUpdatePublisher, controlLoopStateChangePublisher); + } + + @AfterAll + public static void closeDbProvider() throws PfModelException { + clProvider.close(); + modelsProvider.close(); } @Test @@ -104,77 +128,75 @@ class ControlLoopInstantiationProviderTest { InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "Crud"); ControlLoops controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); assertThat(controlLoopsDb.getControlLoopList()).isEmpty(); - try (ControlLoopInstantiationProvider instantiationProvider = new ControlLoopInstantiationProvider( - controlLoopParameters, commissioningProvider, supervisionHandler)) { + var instantiationProvider = + new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler); - // to validate control Loop, it needs to define ToscaServiceTemplate - InstantiationUtils.storeToscaServiceTemplate(TOSCA_TEMPLATE_YAML, commissioningProvider); + // to validate control Loop, it needs to define ToscaServiceTemplate + InstantiationUtils.storeToscaServiceTemplate(TOSCA_TEMPLATE_YAML, commissioningProvider); - InstantiationResponse instantiationResponse = instantiationProvider.createControlLoops(controlLoopsCreate); - InstantiationUtils.assertInstantiationResponse(instantiationResponse, controlLoopsCreate); + InstantiationResponse instantiationResponse = instantiationProvider.createControlLoops(controlLoopsCreate); + InstantiationUtils.assertInstantiationResponse(instantiationResponse, controlLoopsCreate); - controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); - assertThat(controlLoopsDb.getControlLoopList()).isNotEmpty(); - assertThat(controlLoopsCreate).isEqualTo(controlLoopsDb); - - for (ControlLoop controlLoop : controlLoopsCreate.getControlLoopList()) { - ControlLoops controlLoopsGet = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); - assertThat(controlLoop).isEqualTo(controlLoopsGet.getControlLoopList().get(0)); - } + controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); + assertThat(controlLoopsDb.getControlLoopList()).isNotEmpty(); + assertThat(controlLoopsCreate).isEqualTo(controlLoopsDb); - ControlLoops controlLoopsUpdate = - InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_UPDATE_JSON, "Crud"); - assertThat(controlLoopsUpdate).isNotEqualTo(controlLoopsDb); + for (ControlLoop controlLoop : controlLoopsCreate.getControlLoopList()) { + ControlLoops controlLoopsGet = + instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); + assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); + assertThat(controlLoop).isEqualTo(controlLoopsGet.getControlLoopList().get(0)); + } - instantiationResponse = instantiationProvider.updateControlLoops(controlLoopsUpdate); - InstantiationUtils.assertInstantiationResponse(instantiationResponse, controlLoopsUpdate); + ControlLoops controlLoopsUpdate = + InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_UPDATE_JSON, "Crud"); + assertThat(controlLoopsUpdate).isNotEqualTo(controlLoopsDb); - controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); - assertThat(controlLoopsDb.getControlLoopList()).isNotEmpty(); - assertThat(controlLoopsUpdate).isEqualTo(controlLoopsDb); + instantiationResponse = instantiationProvider.updateControlLoops(controlLoopsUpdate); + InstantiationUtils.assertInstantiationResponse(instantiationResponse, controlLoopsUpdate); - InstantiationCommand instantiationCommand = - InstantiationUtils.getInstantiationCommandFromResource(CL_INSTANTIATION_CHANGE_STATE_JSON, "Crud"); - instantiationResponse = instantiationProvider.issueControlLoopCommand(instantiationCommand); - InstantiationUtils.assertInstantiationResponse(instantiationResponse, instantiationCommand); + controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); + assertThat(controlLoopsDb.getControlLoopList()).isNotEmpty(); + assertThat(controlLoopsUpdate).isEqualTo(controlLoopsDb); - for (ToscaConceptIdentifier toscaConceptIdentifier : instantiationCommand.getControlLoopIdentifierList()) { - ControlLoops controlLoopsGet = instantiationProvider.getControlLoops(toscaConceptIdentifier.getName(), - toscaConceptIdentifier.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); - assertThat(instantiationCommand.getOrderedState()) - .isEqualTo(controlLoopsGet.getControlLoopList().get(0).getOrderedState()); - } + InstantiationCommand instantiationCommand = + InstantiationUtils.getInstantiationCommandFromResource(CL_INSTANTIATION_CHANGE_STATE_JSON, "Crud"); + instantiationResponse = instantiationProvider.issueControlLoopCommand(instantiationCommand); + InstantiationUtils.assertInstantiationResponse(instantiationResponse, instantiationCommand); - // in order to delete a controlLoop the state must be UNINITIALISED - controlLoopsCreate.getControlLoopList().forEach(cl -> cl.setState(ControlLoopState.UNINITIALISED)); - instantiationProvider.updateControlLoops(controlLoopsCreate); + for (ToscaConceptIdentifier toscaConceptIdentifier : instantiationCommand.getControlLoopIdentifierList()) { + ControlLoops controlLoopsGet = instantiationProvider.getControlLoops(toscaConceptIdentifier.getName(), + toscaConceptIdentifier.getVersion()); + assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); + assertThat(instantiationCommand.getOrderedState()) + .isEqualTo(controlLoopsGet.getControlLoopList().get(0).getOrderedState()); + } - for (ControlLoop controlLoop : controlLoopsCreate.getControlLoopList()) { - instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); - } + // in order to delete a controlLoop the state must be UNINITIALISED + controlLoopsCreate.getControlLoopList().forEach(cl -> cl.setState(ControlLoopState.UNINITIALISED)); + instantiationProvider.updateControlLoops(controlLoopsCreate); - controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); - assertThat(controlLoopsDb.getControlLoopList()).isEmpty(); + for (ControlLoop controlLoop : controlLoopsCreate.getControlLoopList()) { + instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); } + + controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); + assertThat(controlLoopsDb.getControlLoopList()).isEmpty(); } private ControlLoops getControlLoopsFromDb(ControlLoops controlLoopsSource) throws Exception { ControlLoops controlLoopsDb = new ControlLoops(); controlLoopsDb.setControlLoopList(new ArrayList<>()); - try (ControlLoopInstantiationProvider instantiationProvider = new ControlLoopInstantiationProvider( - controlLoopParameters, commissioningProvider, supervisionHandler)) { + var instantiationProvider = + new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler); - for (ControlLoop controlLoop : controlLoopsSource.getControlLoopList()) { - ControlLoops controlLoopsFromDb = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - controlLoopsDb.getControlLoopList().addAll(controlLoopsFromDb.getControlLoopList()); - } - return controlLoopsDb; + for (ControlLoop controlLoop : controlLoopsSource.getControlLoopList()) { + ControlLoops controlLoopsFromDb = + instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); + controlLoopsDb.getControlLoopList().addAll(controlLoopsFromDb.getControlLoopList()); } + return controlLoopsDb; } @Test @@ -185,37 +207,36 @@ class ControlLoopInstantiationProviderTest { ControlLoop controlLoop0 = controlLoops.getControlLoopList().get(0); - try (ControlLoopInstantiationProvider instantiationProvider = new ControlLoopInstantiationProvider( - controlLoopParameters, commissioningProvider, supervisionHandler)) { + var instantiationProvider = + new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler); - // to validate control Loop, it needs to define ToscaServiceTemplate - InstantiationUtils.storeToscaServiceTemplate(TOSCA_TEMPLATE_YAML, commissioningProvider); + // to validate control Loop, it needs to define ToscaServiceTemplate + InstantiationUtils.storeToscaServiceTemplate(TOSCA_TEMPLATE_YAML, commissioningProvider); - assertThatThrownBy( - () -> instantiationProvider.deleteControlLoop(controlLoop0.getName(), controlLoop0.getVersion())) - .hasMessageMatching(CONTROL_LOOP_NOT_FOUND); + assertThatThrownBy( + () -> instantiationProvider.deleteControlLoop(controlLoop0.getName(), controlLoop0.getVersion())) + .hasMessageMatching(CONTROL_LOOP_NOT_FOUND); - InstantiationUtils.assertInstantiationResponse(instantiationProvider.createControlLoops(controlLoops), - controlLoops); + InstantiationUtils.assertInstantiationResponse(instantiationProvider.createControlLoops(controlLoops), + controlLoops); - for (ControlLoopState state : ControlLoopState.values()) { - if (!ControlLoopState.UNINITIALISED.equals(state)) { - assertThatDeleteThrownBy(controlLoops, state); - } + for (ControlLoopState state : ControlLoopState.values()) { + if (!ControlLoopState.UNINITIALISED.equals(state)) { + assertThatDeleteThrownBy(controlLoops, state); } + } - controlLoop0.setState(ControlLoopState.UNINITIALISED); - instantiationProvider.updateControlLoops(controlLoops); + controlLoop0.setState(ControlLoopState.UNINITIALISED); + instantiationProvider.updateControlLoops(controlLoops); - for (ControlLoop controlLoop : controlLoops.getControlLoopList()) { - instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); - } + for (ControlLoop controlLoop : controlLoops.getControlLoopList()) { + instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); + } - for (ControlLoop controlLoop : controlLoops.getControlLoopList()) { - ControlLoops controlLoopsGet = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).isEmpty(); - } + for (ControlLoop controlLoop : controlLoops.getControlLoopList()) { + ControlLoops controlLoopsGet = + instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); + assertThat(controlLoopsGet.getControlLoopList()).isEmpty(); } } @@ -224,14 +245,13 @@ class ControlLoopInstantiationProviderTest { controlLoop.setState(state); - try (ControlLoopInstantiationProvider instantiationProvider = new ControlLoopInstantiationProvider( - controlLoopParameters, commissioningProvider, supervisionHandler)) { + var instantiationProvider = + new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler); - instantiationProvider.updateControlLoops(controlLoops); - assertThatThrownBy( - () -> instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion())) - .hasMessageMatching(String.format(DELETE_BAD_REQUEST, state)); - } + instantiationProvider.updateControlLoops(controlLoops); + assertThatThrownBy( + () -> instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion())) + .hasMessageMatching(String.format(DELETE_BAD_REQUEST, state)); } @Test @@ -242,21 +262,20 @@ class ControlLoopInstantiationProviderTest { ControlLoops controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); assertThat(controlLoopsDb.getControlLoopList()).isEmpty(); - try (ControlLoopInstantiationProvider instantiationProvider = new ControlLoopInstantiationProvider( - controlLoopParameters, commissioningProvider, supervisionHandler)) { + var instantiationProvider = + new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler); - // to validate control Loop, it needs to define ToscaServiceTemplate - InstantiationUtils.storeToscaServiceTemplate(TOSCA_TEMPLATE_YAML, commissioningProvider); + // to validate control Loop, it needs to define ToscaServiceTemplate + InstantiationUtils.storeToscaServiceTemplate(TOSCA_TEMPLATE_YAML, commissioningProvider); - InstantiationResponse instantiationResponse = instantiationProvider.createControlLoops(controlLoopsCreate); - InstantiationUtils.assertInstantiationResponse(instantiationResponse, controlLoopsCreate); + InstantiationResponse instantiationResponse = instantiationProvider.createControlLoops(controlLoopsCreate); + InstantiationUtils.assertInstantiationResponse(instantiationResponse, controlLoopsCreate); - assertThatThrownBy(() -> instantiationProvider.createControlLoops(controlLoopsCreate)).hasMessageMatching( - controlLoopsCreate.getControlLoopList().get(0).getKey().asIdentifier() + " already defined"); + assertThatThrownBy(() -> instantiationProvider.createControlLoops(controlLoopsCreate)).hasMessageMatching( + controlLoopsCreate.getControlLoopList().get(0).getKey().asIdentifier() + " already defined"); - for (ControlLoop controlLoop : controlLoopsCreate.getControlLoopList()) { - instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); - } + for (ControlLoop controlLoop : controlLoopsCreate.getControlLoopList()) { + instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); } } @@ -265,17 +284,15 @@ class ControlLoopInstantiationProviderTest { ControlLoops controlLoops = InstantiationUtils .getControlLoopsFromResource(CL_INSTANTIATION_DEFINITION_NAME_NOT_FOUND_JSON, "ClElementNotFound"); - try (ControlLoopInstantiationProvider provider = new ControlLoopInstantiationProvider(controlLoopParameters, - commissioningProvider, supervisionHandler)) { + var provider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler); - // to validate control Loop, it needs to define ToscaServiceTemplate - InstantiationUtils.storeToscaServiceTemplate(TOSCA_TEMPLATE_YAML, commissioningProvider); + // to validate control Loop, it needs to define ToscaServiceTemplate + InstantiationUtils.storeToscaServiceTemplate(TOSCA_TEMPLATE_YAML, commissioningProvider); - assertThat(getControlLoopsFromDb(controlLoops).getControlLoopList()).isEmpty(); + assertThat(getControlLoopsFromDb(controlLoops).getControlLoopList()).isEmpty(); - assertThatThrownBy(() -> provider.createControlLoops(controlLoops)) - .hasMessageMatching(CONTROLLOOP_ELEMENT_NAME_NOT_FOUND); - } + assertThatThrownBy(() -> provider.createControlLoops(controlLoops)) + .hasMessageMatching(CONTROLLOOP_ELEMENT_NAME_NOT_FOUND); } @Test @@ -285,20 +302,17 @@ class ControlLoopInstantiationProviderTest { assertThat(getControlLoopsFromDb(controlLoops).getControlLoopList()).isEmpty(); - try (ControlLoopInstantiationProvider provider = new ControlLoopInstantiationProvider(controlLoopParameters, - commissioningProvider, supervisionHandler)) { - assertThatThrownBy(() -> provider.createControlLoops(controlLoops)) - .hasMessageMatching(CONTROLLOOP_DEFINITION_NOT_FOUND); - } + var provider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler); + assertThatThrownBy(() -> provider.createControlLoops(controlLoops)) + .hasMessageMatching(CONTROLLOOP_DEFINITION_NOT_FOUND); } @Test void testIssueControlLoopCommand_OrderedStateInvalid() throws ControlLoopRuntimeException, IOException { - try (ControlLoopInstantiationProvider instantiationProvider = new ControlLoopInstantiationProvider( - controlLoopParameters, commissioningProvider, supervisionHandler)) { - assertThatThrownBy(() -> instantiationProvider.issueControlLoopCommand(new InstantiationCommand())) - .hasMessageMatching(ORDERED_STATE_INVALID); - } + var instantiationProvider = + new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler); + assertThatThrownBy(() -> instantiationProvider.issueControlLoopCommand(new InstantiationCommand())) + .hasMessageMatching(ORDERED_STATE_INVALID); } @Test @@ -309,61 +323,60 @@ class ControlLoopInstantiationProviderTest { InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "V1"); assertThat(getControlLoopsFromDb(controlLoopsV1).getControlLoopList()).isEmpty(); - try (ControlLoopInstantiationProvider instantiationProvider = new ControlLoopInstantiationProvider( - controlLoopParameters, commissioningProvider, supervisionHandler)) { + var instantiationProvider = + new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler); - // to validate control Loop, it needs to define ToscaServiceTemplate - InstantiationUtils.storeToscaServiceTemplate(TOSCA_TEMPLATE_YAML, commissioningProvider); + // to validate control Loop, it needs to define ToscaServiceTemplate + InstantiationUtils.storeToscaServiceTemplate(TOSCA_TEMPLATE_YAML, commissioningProvider); - InstantiationUtils.assertInstantiationResponse(instantiationProvider.createControlLoops(controlLoopsV1), - controlLoopsV1); + InstantiationUtils.assertInstantiationResponse(instantiationProvider.createControlLoops(controlLoopsV1), + controlLoopsV1); - // create controlLoops V2 - ControlLoops controlLoopsV2 = - InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "V2"); - assertThat(getControlLoopsFromDb(controlLoopsV2).getControlLoopList()).isEmpty(); - InstantiationUtils.assertInstantiationResponse(instantiationProvider.createControlLoops(controlLoopsV2), - controlLoopsV2); + // create controlLoops V2 + ControlLoops controlLoopsV2 = + InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "V2"); + assertThat(getControlLoopsFromDb(controlLoopsV2).getControlLoopList()).isEmpty(); + InstantiationUtils.assertInstantiationResponse(instantiationProvider.createControlLoops(controlLoopsV2), + controlLoopsV2); - // GET controlLoops V2 - for (ControlLoop controlLoop : controlLoopsV2.getControlLoopList()) { - ControlLoops controlLoopsGet = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); - assertThat(controlLoop).isEqualTo(controlLoopsGet.getControlLoopList().get(0)); - } + // GET controlLoops V2 + for (ControlLoop controlLoop : controlLoopsV2.getControlLoopList()) { + ControlLoops controlLoopsGet = + instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); + assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); + assertThat(controlLoop).isEqualTo(controlLoopsGet.getControlLoopList().get(0)); + } - // DELETE controlLoops V1 - for (ControlLoop controlLoop : controlLoopsV1.getControlLoopList()) { - instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); - } + // DELETE controlLoops V1 + for (ControlLoop controlLoop : controlLoopsV1.getControlLoopList()) { + instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); + } - // GET controlLoops V1 is not available - for (ControlLoop controlLoop : controlLoopsV1.getControlLoopList()) { - ControlLoops controlLoopsGet = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).isEmpty(); - } + // GET controlLoops V1 is not available + for (ControlLoop controlLoop : controlLoopsV1.getControlLoopList()) { + ControlLoops controlLoopsGet = + instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); + assertThat(controlLoopsGet.getControlLoopList()).isEmpty(); + } - // GET controlLoops V2 is still available - for (ControlLoop controlLoop : controlLoopsV2.getControlLoopList()) { - ControlLoops controlLoopsGet = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); - assertThat(controlLoop).isEqualTo(controlLoopsGet.getControlLoopList().get(0)); - } + // GET controlLoops V2 is still available + for (ControlLoop controlLoop : controlLoopsV2.getControlLoopList()) { + ControlLoops controlLoopsGet = + instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); + assertThat(controlLoopsGet.getControlLoopList()).hasSize(1); + assertThat(controlLoop).isEqualTo(controlLoopsGet.getControlLoopList().get(0)); + } - // DELETE controlLoops V2 - for (ControlLoop controlLoop : controlLoopsV2.getControlLoopList()) { - instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); - } + // DELETE controlLoops V2 + for (ControlLoop controlLoop : controlLoopsV2.getControlLoopList()) { + instantiationProvider.deleteControlLoop(controlLoop.getName(), controlLoop.getVersion()); + } - // GET controlLoops V2 is not available - for (ControlLoop controlLoop : controlLoopsV2.getControlLoopList()) { - ControlLoops controlLoopsGet = - instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); - assertThat(controlLoopsGet.getControlLoopList()).isEmpty(); - } + // GET controlLoops V2 is not available + for (ControlLoop controlLoop : controlLoopsV2.getControlLoopList()) { + ControlLoops controlLoopsGet = + instantiationProvider.getControlLoops(controlLoop.getName(), controlLoop.getVersion()); + assertThat(controlLoopsGet.getControlLoopList()).isEmpty(); } } } diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/main/startstop/ClRuntimeActivatorTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/main/startstop/ClRuntimeActivatorTest.java deleted file mode 100644 index 7eb567259..000000000 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/main/startstop/ClRuntimeActivatorTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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.clamp.controlloop.runtime.main.startstop; - -import static org.assertj.core.api.Assertions.assertThatIllegalStateException; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; -import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; -import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterHandler; -import org.onap.policy.clamp.controlloop.runtime.supervision.SupervisionHandler; - -/** - * Class to perform unit test of {@link ClRuntimeActivator}}. - * - */ -class ClRuntimeActivatorTest { - - @Test - void testStartAndStop() throws Exception { - final String path = "src/test/resources/parameters/TestParameters.json"; - ClRuntimeParameterGroup parameterGroup = new ClRuntimeParameterHandler().getParameters(path); - var supervisionHandler = Mockito.mock(SupervisionHandler.class); - - try (var activator = new ClRuntimeActivator(parameterGroup, supervisionHandler)) { - - assertFalse(activator.isAlive()); - activator.start(); - assertTrue(activator.isAlive()); - assertTrue(activator.getParameterGroup().isValid()); - - // repeat start - should throw an exception - assertThatIllegalStateException().isThrownBy(() -> activator.start()); - assertTrue(activator.isAlive()); - assertTrue(activator.getParameterGroup().isValid()); - - activator.stop(); - assertFalse(activator.isAlive()); - - // repeat stop - should throw an exception - assertThatIllegalStateException().isThrownBy(() -> activator.stop()); - assertFalse(activator.isAlive()); - } - } -} diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/TestMonitoringProvider.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/TestMonitoringProvider.java index 580b30f9e..c47211a2d 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/TestMonitoringProvider.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/TestMonitoringProvider.java @@ -23,15 +23,15 @@ package org.onap.policy.clamp.controlloop.runtime.monitoring; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import java.io.File; -import java.lang.reflect.Field; import java.time.Instant; -import java.util.ArrayList; import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -39,7 +39,9 @@ import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ClElementSt import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantStatisticsList; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ClElementStatisticsProvider; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ParticipantStatisticsProvider; import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; import org.onap.policy.clamp.controlloop.runtime.util.CommonTestData; import org.onap.policy.common.utils.coder.Coder; @@ -59,14 +61,16 @@ class TestMonitoringProvider { "src/test/resources/rest/monitoring/TestClElementStatistics_Invalid.json"; private static final Coder CODER = new StandardCoder(); - private static final String CL_PROVIDER_FIELD = "controlLoopProvider"; - private static final String LIST_IS_NULL = ".*StatisticsList is marked .*ull but is null"; private static ParticipantStatisticsList inputParticipantStatistics; private static ParticipantStatisticsList invalidParticipantInput; private static ClElementStatisticsList inputClElementStatistics; private static ClElementStatisticsList invalidClElementInput; + private ParticipantStatisticsProvider participantStatisticsProvider = null; + private ClElementStatisticsProvider clElementStatisticsProvider = null; + private ControlLoopProvider clProvider = null; + @BeforeAll public static void beforeSetupStatistics() throws CoderException { // Reading input json for statistics data @@ -78,141 +82,167 @@ class TestMonitoringProvider { invalidClElementInput = CODER.decode(new File(INVALID_CL_ELEMENT_JSON_INPUT), ClElementStatisticsList.class); } + @AfterEach + void close() throws Exception { + if (participantStatisticsProvider != null) { + participantStatisticsProvider.close(); + } + if (clElementStatisticsProvider != null) { + clElementStatisticsProvider.close(); + } + if (clProvider != null) { + clProvider.close(); + } + } + @Test void testCreateParticipantStatistics() throws Exception { ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup(0, "createparStat"); - - try (MonitoringProvider provider = new MonitoringProvider(parameters)) { - // Creating statistics data in db with null input - assertThatThrownBy(() -> { - provider.createParticipantStatistics(null); - }).hasMessageMatching(LIST_IS_NULL); - - assertThatThrownBy(() -> { - provider.createParticipantStatistics(invalidParticipantInput.getStatisticsList()); - }).hasMessageMatching("participantStatisticsList is marked .*null but is null"); - - // Creating statistics data from input json - ParticipantStatisticsList createResponse = - provider.createParticipantStatistics(inputParticipantStatistics.getStatisticsList()); - - assertThat(createResponse.getStatisticsList()).hasSize(3); - assertEquals(createResponse.getStatisticsList().toString().replaceAll("\\s+", ""), - inputParticipantStatistics.getStatisticsList().toString().replaceAll("\\s+", "")); - } + participantStatisticsProvider = new ParticipantStatisticsProvider(parameters.getDatabaseProviderParameters()); + clElementStatisticsProvider = new ClElementStatisticsProvider(parameters.getDatabaseProviderParameters()); + clProvider = new ControlLoopProvider(parameters.getDatabaseProviderParameters()); + MonitoringProvider provider = + new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider); + // Creating statistics data in db with null input + assertThatThrownBy(() -> { + provider.createParticipantStatistics(null); + }).hasMessageMatching(LIST_IS_NULL); + + assertThatThrownBy(() -> { + provider.createParticipantStatistics(invalidParticipantInput.getStatisticsList()); + }).hasMessageMatching("participantStatisticsList is marked .*null but is null"); + + // Creating statistics data from input json + ParticipantStatisticsList createResponse = + provider.createParticipantStatistics(inputParticipantStatistics.getStatisticsList()); + + assertThat(createResponse.getStatisticsList()).hasSize(3); + assertEquals(createResponse.getStatisticsList().toString().replaceAll("\\s+", ""), + inputParticipantStatistics.getStatisticsList().toString().replaceAll("\\s+", "")); } @Test void testGetParticipantStatistics() throws Exception { ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup(0, "getparStat"); - try (MonitoringProvider provider = new MonitoringProvider(parameters)) { - ParticipantStatisticsList getResponse; - - provider.createParticipantStatistics(inputParticipantStatistics.getStatisticsList()); - - assertThatThrownBy(() -> { - provider.fetchFilteredParticipantStatistics(null, null, 0, null, null); - }).hasMessageMatching("name is marked .*null but is null"); - - // Fetch specific statistics record with name, version and record count - getResponse = provider.fetchFilteredParticipantStatistics("name2", "1.001", 1, null, null); - assertThat(getResponse.getStatisticsList()).hasSize(1); - assertEquals(getResponse.getStatisticsList().get(0).toString().replaceAll("\\s+", ""), - inputParticipantStatistics.getStatisticsList().get(2).toString().replaceAll("\\s+", "")); - - // Fetch statistics using timestamp - getResponse = provider.fetchFilteredParticipantStatistics("name1", "1.001", 0, null, - Instant.parse("2021-01-10T15:00:00.000Z")); - assertThat(getResponse.getStatisticsList()).hasSize(1); - - getResponse = provider.fetchFilteredParticipantStatistics("name1", "1.001", 0, - Instant.parse("2021-01-11T12:00:00.000Z"), Instant.parse("2021-01-11T16:00:00.000Z")); - - assertThat(getResponse.getStatisticsList()).isEmpty(); - } + participantStatisticsProvider = new ParticipantStatisticsProvider(parameters.getDatabaseProviderParameters()); + clElementStatisticsProvider = new ClElementStatisticsProvider(parameters.getDatabaseProviderParameters()); + clProvider = new ControlLoopProvider(parameters.getDatabaseProviderParameters()); + MonitoringProvider provider = + new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider); + + provider.createParticipantStatistics(inputParticipantStatistics.getStatisticsList()); + + assertThatThrownBy(() -> { + provider.fetchFilteredParticipantStatistics(null, null, 0, null, null); + }).hasMessageMatching("name is marked .*null but is null"); + + // Fetch specific statistics record with name, version and record count + ParticipantStatisticsList getResponse = + provider.fetchFilteredParticipantStatistics("name2", "1.001", 1, null, null); + assertThat(getResponse.getStatisticsList()).hasSize(1); + assertEquals(getResponse.getStatisticsList().get(0).toString().replaceAll("\\s+", ""), + inputParticipantStatistics.getStatisticsList().get(2).toString().replaceAll("\\s+", "")); + + // Fetch statistics using timestamp + getResponse = provider.fetchFilteredParticipantStatistics("name1", "1.001", 0, null, + Instant.parse("2021-01-10T15:00:00.000Z")); + assertThat(getResponse.getStatisticsList()).hasSize(1); + + getResponse = provider.fetchFilteredParticipantStatistics("name1", "1.001", 0, + Instant.parse("2021-01-11T12:00:00.000Z"), Instant.parse("2021-01-11T16:00:00.000Z")); + + assertThat(getResponse.getStatisticsList()).isEmpty(); } @Test void testCreateClElementStatistics() throws Exception { ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup(0, "createelemstat"); - - try (MonitoringProvider provider = new MonitoringProvider(parameters)) { - // Creating statistics data in db with null input - assertThatThrownBy(() -> { - provider.createClElementStatistics(null); - }).hasMessageMatching(LIST_IS_NULL); - - assertThatThrownBy(() -> { - provider.createClElementStatistics(invalidClElementInput.getClElementStatistics()); - }).hasMessageMatching("clElementStatisticsList is marked .*null but is null"); - - // Creating clElement statistics data from input json - ClElementStatisticsList createResponse = - provider.createClElementStatistics(inputClElementStatistics.getClElementStatistics()); - - assertThat(createResponse.getClElementStatistics()).hasSize(4); - assertEquals(createResponse.getClElementStatistics().toString().replaceAll("\\s+", ""), - inputClElementStatistics.getClElementStatistics().toString().replaceAll("\\s+", "")); - } + participantStatisticsProvider = new ParticipantStatisticsProvider(parameters.getDatabaseProviderParameters()); + clElementStatisticsProvider = new ClElementStatisticsProvider(parameters.getDatabaseProviderParameters()); + clProvider = new ControlLoopProvider(parameters.getDatabaseProviderParameters()); + + MonitoringProvider provider = + new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider); + // Creating statistics data in db with null input + assertThatThrownBy(() -> { + provider.createClElementStatistics(null); + }).hasMessageMatching(LIST_IS_NULL); + + assertThatThrownBy(() -> { + provider.createClElementStatistics(invalidClElementInput.getClElementStatistics()); + }).hasMessageMatching("clElementStatisticsList is marked .*null but is null"); + + // Creating clElement statistics data from input json + ClElementStatisticsList createResponse = + provider.createClElementStatistics(inputClElementStatistics.getClElementStatistics()); + + assertThat(createResponse.getClElementStatistics()).hasSize(4); + assertEquals(createResponse.getClElementStatistics().toString().replaceAll("\\s+", ""), + inputClElementStatistics.getClElementStatistics().toString().replaceAll("\\s+", "")); } @Test void testGetClElementStatistics() throws Exception { ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup(0, "getelemstat"); + participantStatisticsProvider = new ParticipantStatisticsProvider(parameters.getDatabaseProviderParameters()); + clElementStatisticsProvider = new ClElementStatisticsProvider(parameters.getDatabaseProviderParameters()); + clProvider = new ControlLoopProvider(parameters.getDatabaseProviderParameters()); - try (MonitoringProvider provider = new MonitoringProvider(parameters)) { - ClElementStatisticsList getResponse; + MonitoringProvider provider = + new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider); - assertThatThrownBy(() -> { - provider.fetchFilteredClElementStatistics(null, null, null, null, null, 0); - }).hasMessageMatching("name is marked .*null but is null"); + assertThatThrownBy(() -> { + provider.fetchFilteredClElementStatistics(null, null, null, null, null, 0); + }).hasMessageMatching("name is marked .*null but is null"); - provider.createClElementStatistics(inputClElementStatistics.getClElementStatistics()); + provider.createClElementStatistics(inputClElementStatistics.getClElementStatistics()); - getResponse = provider.fetchFilteredClElementStatistics("name1", null, null, null, null, 0); + ClElementStatisticsList getResponse = + provider.fetchFilteredClElementStatistics("name1", null, null, null, null, 0); - assertThat(getResponse.getClElementStatistics()).hasSize(2); - assertEquals(getResponse.getClElementStatistics().get(0).toString().replaceAll("\\s+", ""), - inputClElementStatistics.getClElementStatistics().get(0).toString().replaceAll("\\s+", "")); + assertThat(getResponse.getClElementStatistics()).hasSize(2); + assertEquals(getResponse.getClElementStatistics().get(0).toString().replaceAll("\\s+", ""), + inputClElementStatistics.getClElementStatistics().get(0).toString().replaceAll("\\s+", "")); - // Fetch specific statistics record with name, id and record count - getResponse = provider.fetchFilteredClElementStatistics("name1", "1.001", - "709c62b3-8918-41b9-a747-d21eb79c6c20", null, null, 0); - assertThat(getResponse.getClElementStatistics()).hasSize(2); + // Fetch specific statistics record with name, id and record count + getResponse = provider.fetchFilteredClElementStatistics("name1", "1.001", + "709c62b3-8918-41b9-a747-d21eb79c6c20", null, null, 0); + assertThat(getResponse.getClElementStatistics()).hasSize(2); - // Fetch statistics using timestamp - getResponse = provider.fetchFilteredClElementStatistics("name1", "1.001", null, - Instant.parse("2021-01-10T13:45:00.000Z"), null, 0); - assertThat(getResponse.getClElementStatistics()).hasSize(2); - } + // Fetch statistics using timestamp + getResponse = provider.fetchFilteredClElementStatistics("name1", "1.001", null, + Instant.parse("2021-01-10T13:45:00.000Z"), null, 0); + assertThat(getResponse.getClElementStatistics()).hasSize(2); } @Test void testGetParticipantStatsPerCL() throws Exception { ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup(0, "getparStatCL"); - - try (MonitoringProvider provider = Mockito.spy(new MonitoringProvider(parameters))) { - - provider.createParticipantStatistics(inputParticipantStatistics.getStatisticsList()); - // Mock the response for fetching participant conceptIdentifiers per control loop - List<ToscaConceptIdentifier> conceptIdentifiers = new ArrayList<>(); - conceptIdentifiers.add(new ToscaConceptIdentifier("name1", "1.001")); - when(provider.getAllParticipantIdsPerControlLoop("testName", "1.001")).thenReturn(conceptIdentifiers); - ParticipantStatisticsList getResponse; - getResponse = provider.fetchParticipantStatsPerControlLoop("testName", "1.001"); - assertThat(getResponse.getStatisticsList()).hasSize(2); - assertEquals(getResponse.getStatisticsList().get(0).toString().replaceAll("\\s+", ""), - inputParticipantStatistics.getStatisticsList().get(0).toString().replaceAll("\\s+", "")); - assertThat(provider.fetchParticipantStatsPerControlLoop("invalidCLName", "1.002").getStatisticsList()) - .isEmpty(); - } - + participantStatisticsProvider = new ParticipantStatisticsProvider(parameters.getDatabaseProviderParameters()); + clElementStatisticsProvider = new ClElementStatisticsProvider(parameters.getDatabaseProviderParameters()); + var mockClProvider = Mockito.mock(ControlLoopProvider.class); + var provider = + new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, mockClProvider); + + provider.createParticipantStatistics(inputParticipantStatistics.getStatisticsList()); + + var controlLoop = new ControlLoop(); + var element = new ControlLoopElement(); + element.setParticipantId(new ToscaConceptIdentifier("name1", "1.001")); + controlLoop.setElements(Map.of(UUID.randomUUID(), element)); + when(mockClProvider.getControlLoop(eq(new ToscaConceptIdentifier("testName", "1.001")))) + .thenReturn(controlLoop); + + ParticipantStatisticsList getResponse = provider.fetchParticipantStatsPerControlLoop("testName", "1.001"); + assertThat(getResponse.getStatisticsList()).hasSize(2); + assertEquals(getResponse.getStatisticsList().get(0).toString().replaceAll("\\s+", ""), + inputParticipantStatistics.getStatisticsList().get(0).toString().replaceAll("\\s+", "")); + assertThat(provider.fetchParticipantStatsPerControlLoop("invalidCLName", "1.002").getStatisticsList()) + .isEmpty(); } @Test void testClElementStatsPerCL() throws Exception { - ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup(0, "getelemstatPerCL"); - // Setup a dummy Control loop data ControlLoopElement mockClElement = new ControlLoopElement(); mockClElement.setId(inputClElementStatistics.getClElementStatistics().get(0).getId()); @@ -223,30 +253,32 @@ class TestMonitoringProvider { mockCL.setElements(new LinkedHashMap<>()); mockCL.getElements().put(mockClElement.getId(), mockClElement); - // Mock controlloop data to be returned for the given CL Id + ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup(0, "getelemstatPerCL"); + participantStatisticsProvider = new ParticipantStatisticsProvider(parameters.getDatabaseProviderParameters()); + clElementStatisticsProvider = new ClElementStatisticsProvider(parameters.getDatabaseProviderParameters()); ControlLoopProvider mockClProvider = Mockito.mock(ControlLoopProvider.class); + var monitoringProvider = + new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, mockClProvider); + + // Mock controlloop data to be returned for the given CL Id when(mockClProvider.getControlLoop(new ToscaConceptIdentifier("testCLName", "1.001"))).thenReturn(mockCL); - try (MonitoringProvider monitoringProvider = new MonitoringProvider(parameters)) { - monitoringProvider.createClElementStatistics(inputClElementStatistics.getClElementStatistics()); - Field controlLoopProviderField = monitoringProvider.getClass().getDeclaredField(CL_PROVIDER_FIELD); - controlLoopProviderField.setAccessible(true); - controlLoopProviderField.set(monitoringProvider, mockClProvider); + monitoringProvider.createClElementStatistics(inputClElementStatistics.getClElementStatistics()); - ClElementStatisticsList getResponse; - getResponse = monitoringProvider.fetchClElementStatsPerControlLoop("testCLName", "1.001"); + ClElementStatisticsList getResponse; + getResponse = monitoringProvider.fetchClElementStatsPerControlLoop("testCLName", "1.001"); - assertThat(getResponse.getClElementStatistics()).hasSize(2); - assertEquals(getResponse.getClElementStatistics().get(1).toString().replaceAll("\\s+", ""), - inputClElementStatistics.getClElementStatistics().get(1).toString().replaceAll("\\s+", "")); + assertThat(getResponse.getClElementStatistics()).hasSize(2); + assertEquals(getResponse.getClElementStatistics().get(1).toString().replaceAll("\\s+", ""), + inputClElementStatistics.getClElementStatistics().get(1).toString().replaceAll("\\s+", "")); - assertThat(monitoringProvider.fetchClElementStatsPerControlLoop("invalidCLName", "1.002") - .getClElementStatistics()).isEmpty(); + assertThat( + monitoringProvider.fetchClElementStatsPerControlLoop("invalidCLName", "1.002").getClElementStatistics()) + .isEmpty(); - Map<String, ToscaConceptIdentifier> clElementIds = - monitoringProvider.getAllClElementsIdPerControlLoop("testCLName", "1.001"); - assertThat(clElementIds) - .containsKey(inputClElementStatistics.getClElementStatistics().get(0).getId().toString()); - } + Map<String, ToscaConceptIdentifier> clElementIds = + monitoringProvider.getAllClElementsIdPerControlLoop("testCLName", "1.001"); + assertThat(clElementIds) + .containsKey(inputClElementStatistics.getClElementStatistics().get(0).getId().toString()); } } diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/rest/MonitoringQueryControllerTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/rest/MonitoringQueryControllerTest.java index 95b2113cd..77742aea9 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/rest/MonitoringQueryControllerTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/rest/MonitoringQueryControllerTest.java @@ -34,7 +34,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ClElementStatisticsList; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantStatisticsList; -import org.onap.policy.clamp.controlloop.runtime.main.parameters.ClRuntimeParameterGroup; import org.onap.policy.clamp.controlloop.runtime.monitoring.MonitoringProvider; import org.onap.policy.clamp.controlloop.runtime.util.rest.CommonRestController; import org.onap.policy.common.utils.coder.Coder; @@ -70,7 +69,7 @@ class MonitoringQueryControllerTest extends CommonRestController { private static final String CLELEMENT_STATS_PER_CL_ENDPOINT = "monitoring/clelements/controlloop"; @Autowired - private ClRuntimeParameterGroup clRuntimeParameterGroup; + private MonitoringProvider monitoringProvider; @LocalServerPort private int randomServerPort; @@ -92,14 +91,12 @@ class MonitoringQueryControllerTest extends CommonRestController { public void setUpBeforeEach() throws Exception { super.setHttpPrefix(randomServerPort); - try (var monitoringProvider = new MonitoringProvider(clRuntimeParameterGroup)) { - // Insert Participant statistics to DB - participantStatisticsList = - monitoringProvider.createParticipantStatistics(inputParticipantStatistics.getStatisticsList()); - // Insert CL Element statistics to DB - clElementStatisticsList = - monitoringProvider.createClElementStatistics(inputClElementStatistics.getClElementStatistics()); - } + // Insert Participant statistics to DB + participantStatisticsList = + monitoringProvider.createParticipantStatistics(inputParticipantStatistics.getStatisticsList()); + // Insert CL Element statistics to DB + clElementStatisticsList = + monitoringProvider.createClElementStatistics(inputClElementStatistics.getClElementStatistics()); } @Test diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/util/CommonTestData.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/util/CommonTestData.java index aa17e9c4f..464c14354 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/util/CommonTestData.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/util/CommonTestData.java @@ -27,6 +27,11 @@ import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.provider.PolicyModelsProvider; +import org.onap.policy.models.provider.PolicyModelsProviderFactory; +import org.onap.policy.models.provider.PolicyModelsProviderParameters; /** * Class to hold/create all parameters for test cases. @@ -63,4 +68,19 @@ public class CommonTestData { return ResourceUtils.getResourceAsString("src/test/resources/parameters/InstantiationConfigParametersStd.json") .replace("${port}", String.valueOf(port)).replace("${dbName}", "jdbc:h2:mem:" + dbName); } + + /** + * Create a new PolicyModelsProvider. + * + * @param databaseProviderParameters the database Provider Parameters + * @return a new PolicyModelsProvider + */ + public static PolicyModelsProvider getPolicyModelsProvider( + PolicyModelsProviderParameters databaseProviderParameters) { + try { + return new PolicyModelsProviderFactory().createPolicyModelsProvider(databaseProviderParameters); + } catch (PfModelException e) { + throw new PfModelRuntimeException(e); + } + } } diff --git a/runtime-controlloop/src/test/resources/parameters/TestParameters.json b/runtime-controlloop/src/test/resources/parameters/TestParameters.json index 9bcd764cb..680e070f2 100644 --- a/runtime-controlloop/src/test/resources/parameters/TestParameters.json +++ b/runtime-controlloop/src/test/resources/parameters/TestParameters.json @@ -50,13 +50,6 @@ "localhost" ], "topicCommInfrastructure": "dmaap" - }, - { - "topic": "POLICY-NOTIFICATION", - "servers": [ - "localhost" - ], - "topicCommInfrastructure": "dmaap" } ] } |