Migrate pap startup & controllers to spring boot
[policy/pap.git] / main / src / main / java / org / onap / policy / pap / main / startstop / PapActivator.java
index 78a301f..9494370 100644 (file)
@@ -2,6 +2,7 @@
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2019 Nordix Foundation.
  *  Modifications Copyright (C) 2019-2021 AT&T Intellectual Property.
+ *  Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 
 package org.onap.policy.pap.main.startstop;
 
-import java.util.Arrays;
+import java.util.List;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicReference;
 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
+import org.onap.policy.common.endpoints.event.comm.TopicListener;
 import org.onap.policy.common.endpoints.event.comm.TopicSource;
-import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
-import org.onap.policy.common.endpoints.http.server.RestServer;
 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
 import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher;
 import org.onap.policy.common.parameters.ParameterService;
@@ -49,20 +49,12 @@ import org.onap.policy.pap.main.comm.TimerManager;
 import org.onap.policy.pap.main.notification.PolicyNotifier;
 import org.onap.policy.pap.main.parameters.PapParameterGroup;
 import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams;
-import org.onap.policy.pap.main.rest.HealthCheckRestControllerV1;
-import org.onap.policy.pap.main.rest.PapAafFilter;
 import org.onap.policy.pap.main.rest.PapStatisticsManager;
-import org.onap.policy.pap.main.rest.PdpGroupCreateOrUpdateControllerV1;
-import org.onap.policy.pap.main.rest.PdpGroupDeleteControllerV1;
-import org.onap.policy.pap.main.rest.PdpGroupDeployControllerV1;
-import org.onap.policy.pap.main.rest.PdpGroupHealthCheckControllerV1;
-import org.onap.policy.pap.main.rest.PdpGroupQueryControllerV1;
-import org.onap.policy.pap.main.rest.PdpGroupStateChangeControllerV1;
-import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckControllerV1;
-import org.onap.policy.pap.main.rest.PolicyComponentsHealthCheckProvider;
-import org.onap.policy.pap.main.rest.PolicyStatusControllerV1;
 import org.onap.policy.pap.main.rest.PolicyUndeployerImpl;
-import org.onap.policy.pap.main.rest.StatisticsRestControllerV1;
+import org.springframework.context.event.ContextClosedEvent;
+import org.springframework.context.event.ContextRefreshedEvent;
+import org.springframework.context.event.EventListener;
+import org.springframework.stereotype.Component;
 
 /**
  * This class activates Policy Administration (PAP) as a complete service together with all its controllers, listeners &
@@ -70,6 +62,7 @@ import org.onap.policy.pap.main.rest.StatisticsRestControllerV1;
  *
  * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
  */
+@Component
 public class PapActivator extends ServiceManagerContainer {
     private static final String[] MSG_TYPE_NAMES = { "messageName" };
     private static final String[] REQ_ID_NAMES = { "response", "responseTo" };
@@ -79,19 +72,21 @@ public class PapActivator extends ServiceManagerContainer {
      */
     private static final int MAX_MISSED_HEARTBEATS = 3;
 
-    private final PapParameterGroup papParameterGroup;
+    private PapParameterGroup papParameterGroup;
 
     /**
      * Listens for messages on the topic, decodes them into a {@link PdpStatus} message, and then dispatches them to
-     * {@link #reqIdDispatcher}.
+     * {@link #responseReqIdDispatcher}.
      */
-    private final MessageTypeDispatcher msgDispatcher;
+    private final MessageTypeDispatcher responseMsgDispatcher;
+    private final MessageTypeDispatcher heartbeatMsgDispatcher;
 
     /**
      * Listens for {@link PdpStatus} messages and then routes them to the listener associated with the ID of the
      * originating request.
      */
-    private final RequestIdDispatcher<PdpStatus> reqIdDispatcher;
+    private final RequestIdDispatcher<PdpStatus> responseReqIdDispatcher;
+    private final RequestIdDispatcher<PdpStatus> heartbeatReqIdDispatcher;
 
     /**
      * Listener for anonymous {@link PdpStatus} messages either for registration or heartbeat.
@@ -103,22 +98,23 @@ public class PapActivator extends ServiceManagerContainer {
      *
      * @param papParameterGroup the parameters for the pap service
      */
-    public PapActivator(final PapParameterGroup papParameterGroup) {
+    public PapActivator(PapParameterGroup papParameterGroup) {
         super("Policy PAP");
-
+        this.papParameterGroup = papParameterGroup;
         TopicEndpointManager.getManager().addTopics(papParameterGroup.getTopicParameterGroup());
 
         try {
-            this.papParameterGroup = papParameterGroup;
-            this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
-            this.reqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
-            this.pdpHeartbeatListener = new PdpHeartbeatListener(papParameterGroup.getPdpParameters());
+            this.responseMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
+            this.heartbeatMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
+            this.responseReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
+            this.heartbeatReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES);
+            this.pdpHeartbeatListener = new PdpHeartbeatListener(papParameterGroup.getPdpParameters(),
+                            papParameterGroup.isSavePdpStatisticsInDb());
 
         } catch (final RuntimeException e) {
             throw new PolicyPapRuntimeException(e);
         }
 
-        papParameterGroup.getRestServerParameters().setName(papParameterGroup.getName());
 
         final var pdpUpdateLock = new Object();
         final var pdpParams = papParameterGroup.getPdpParameters();
@@ -129,7 +125,6 @@ public class PapActivator extends ServiceManagerContainer {
         final AtomicReference<ScheduledExecutorService> pdpExpirationTimer = new AtomicReference<>();
         final AtomicReference<PolicyModelsProviderFactoryWrapper> daoFactory = new AtomicReference<>();
         final AtomicReference<PdpModifyRequestMap> requestMap = new AtomicReference<>();
-        final AtomicReference<RestServer> restServer = new AtomicReference<>();
         final AtomicReference<PolicyNotifier> notifier = new AtomicReference<>();
 
         // @formatter:off
@@ -147,16 +142,24 @@ public class PapActivator extends ServiceManagerContainer {
             () -> Registry.unregister(PapConstants.REG_PAP_DAO_FACTORY));
 
         addAction("Pdp Heartbeat Listener",
-            () -> reqIdDispatcher.register(pdpHeartbeatListener),
-            () -> reqIdDispatcher.unregister(pdpHeartbeatListener));
+            () -> heartbeatReqIdDispatcher.register(pdpHeartbeatListener),
+            () -> heartbeatReqIdDispatcher.unregister(pdpHeartbeatListener));
+
+        addAction("Response Request ID Dispatcher",
+            () -> responseMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.responseReqIdDispatcher),
+            () -> responseMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
+
+        addAction("Heartbeat Request ID Dispatcher",
+            () -> heartbeatMsgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.heartbeatReqIdDispatcher),
+            () -> heartbeatMsgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
 
-        addAction("Request ID Dispatcher",
-            () -> msgDispatcher.register(PdpMessageType.PDP_STATUS.name(), this.reqIdDispatcher),
-            () -> msgDispatcher.unregister(PdpMessageType.PDP_STATUS.name()));
+        addAction("Response Message Dispatcher",
+            () -> registerMsgDispatcher(responseMsgDispatcher, PapConstants.TOPIC_POLICY_PDP_PAP),
+            () -> unregisterMsgDispatcher(responseMsgDispatcher, PapConstants.TOPIC_POLICY_PDP_PAP));
 
-        addAction("Message Dispatcher",
-            this::registerMsgDispatcher,
-            this::unregisterMsgDispatcher);
+        addAction("Heartbeat Message Dispatcher",
+            () -> registerMsgDispatcher(heartbeatMsgDispatcher, PapConstants.TOPIC_POLICY_HEARTBEAT),
+            () -> unregisterMsgDispatcher(heartbeatMsgDispatcher, PapConstants.TOPIC_POLICY_HEARTBEAT));
 
         addAction("topics",
             TopicEndpointManager.getManager()::start,
@@ -166,6 +169,10 @@ public class PapActivator extends ServiceManagerContainer {
             () -> Registry.register(PapConstants.REG_STATISTICS_MANAGER, new PapStatisticsManager()),
             () -> Registry.unregister(PapConstants.REG_STATISTICS_MANAGER));
 
+        addAction("PAP Activator",
+            () -> Registry.register(PapConstants.REG_PAP_ACTIVATOR, this),
+            () -> Registry.unregister(PapConstants.REG_PAP_ACTIVATOR));
+
         addAction("PDP publisher",
             () -> {
                 pdpPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_PDP_PAP));
@@ -213,9 +220,10 @@ public class PapActivator extends ServiceManagerContainer {
                                     .params(pdpParams)
                                     .policyNotifier(notifier.get())
                                     .pdpPublisher(pdpPub.get())
-                                    .responseDispatcher(reqIdDispatcher)
+                                    .responseDispatcher(responseReqIdDispatcher)
                                     .stateChangeTimers(pdpStChgTimers.get())
                                     .updateTimers(pdpUpdTimers.get())
+                                    .savePdpStatistics(papParameterGroup.isSavePdpStatisticsInDb())
                                     .build()));
                 Registry.register(PapConstants.REG_PDP_MODIFY_MAP, requestMap.get());
 
@@ -234,31 +242,8 @@ public class PapActivator extends ServiceManagerContainer {
                     frequencyMs,
                     TimeUnit.MILLISECONDS);
             },
-            () -> pdpExpirationTimer.get().shutdownNow());
-
-        addAction("PAP client executor",
-            () ->
-                PolicyComponentsHealthCheckProvider.initializeClientHealthCheckExecutorService(papParameterGroup,
-                                HttpClientFactoryInstance.getClientFactory()),
-                PolicyComponentsHealthCheckProvider::cleanup);
+            () -> pdpExpirationTimer.get().shutdown());
 
-        addAction("REST server",
-            () -> {
-                var server = new RestServer(papParameterGroup.getRestServerParameters(), PapAafFilter.class,
-                                HealthCheckRestControllerV1.class,
-                                StatisticsRestControllerV1.class,
-                                PdpGroupCreateOrUpdateControllerV1.class,
-                                PdpGroupDeployControllerV1.class,
-                                PdpGroupDeleteControllerV1.class,
-                                PdpGroupStateChangeControllerV1.class,
-                                PdpGroupQueryControllerV1.class,
-                                PdpGroupHealthCheckControllerV1.class,
-                                PolicyStatusControllerV1.class,
-                                PolicyComponentsHealthCheckControllerV1.class);
-                restServer.set(server);
-                restServer.get().start();
-            },
-            () -> restServer.get().stop());
         // @formatter:on
     }
 
@@ -285,21 +270,47 @@ public class PapActivator extends ServiceManagerContainer {
 
     /**
      * Registers the dispatcher with the topic source(s).
+     * @param dispatcher dispatcher to register
+     * @param topic topic of interest
      */
-    private void registerMsgDispatcher() {
-        for (final TopicSource source : TopicEndpointManager.getManager()
-                .getTopicSources(Arrays.asList(PapConstants.TOPIC_POLICY_PDP_PAP))) {
-            source.register(msgDispatcher);
+    private void registerMsgDispatcher(TopicListener dispatcher, String topic) {
+        for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
+            source.register(dispatcher);
         }
     }
 
     /**
      * Unregisters the dispatcher from the topic source(s).
+     * @param dispatcher dispatcher to unregister
+     * @param topic topic of interest
+     */
+    private void unregisterMsgDispatcher(TopicListener dispatcher, String topic) {
+        for (final TopicSource source : TopicEndpointManager.getManager().getTopicSources(List.of(topic))) {
+            source.unregister(dispatcher);
+        }
+    }
+
+    /**
+     * Handle ContextRefreshEvent.
+     *
+     * @param ctxRefreshedEvent the ContextRefreshedEvent
+     */
+    @EventListener
+    public void handleContextRefreshEvent(ContextRefreshedEvent ctxRefreshedEvent) {
+        if (!isAlive()) {
+            start();
+        }
+    }
+
+    /**
+     * Handle ContextClosedEvent.
+     *
+     * @param ctxClosedEvent the ContextClosedEvent
      */
-    private void unregisterMsgDispatcher() {
-        for (final TopicSource source : TopicEndpointManager.getManager()
-                .getTopicSources(Arrays.asList(PapConstants.TOPIC_POLICY_PDP_PAP))) {
-            source.unregister(msgDispatcher);
+    @EventListener
+    public void handleContextClosedEvent(ContextClosedEvent ctxClosedEvent) {
+        if (isAlive()) {
+            stop();
         }
     }
 }