Java 17 Upgrade
[policy/models.git] / models-sim / policy-models-sim-pdp / src / main / java / org / onap / policy / models / sim / pdp / PdpSimulatorActivator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  *  Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.models.sim.pdp;
23
24 import java.util.List;
25 import java.util.Random;
26 import lombok.Getter;
27 import lombok.Setter;
28 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
29 import org.onap.policy.common.endpoints.event.comm.TopicSink;
30 import org.onap.policy.common.endpoints.event.comm.TopicSource;
31 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
32 import org.onap.policy.common.utils.services.Registry;
33 import org.onap.policy.common.utils.services.ServiceManager;
34 import org.onap.policy.common.utils.services.ServiceManagerException;
35 import org.onap.policy.models.pdp.enums.PdpMessageType;
36 import org.onap.policy.models.sim.pdp.comm.PdpStateChangeListener;
37 import org.onap.policy.models.sim.pdp.comm.PdpStatusPublisher;
38 import org.onap.policy.models.sim.pdp.comm.PdpUpdateListener;
39 import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException;
40 import org.onap.policy.models.sim.pdp.exception.PdpSimulatorRunTimeException;
41 import org.onap.policy.models.sim.pdp.handler.PdpMessageHandler;
42 import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterGroup;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * This class activates the PdpSimulator as a complete service together with all its handlers.
48  *
49  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
50  */
51 public class PdpSimulatorActivator {
52
53     private static final Logger LOGGER = LoggerFactory.getLogger(PdpSimulatorActivator.class);
54     private final PdpSimulatorParameterGroup pdpSimulatorParameterGroup;
55     private final List<TopicSink> topicSinks; // topics to which pdp sends pdp status
56     private final List<TopicSource> topicSources; // topics to which pdp listens to for messages from pap.
57     private static final String[] MSG_TYPE_NAMES = { "messageName" };
58
59     /*
60      * This simulator is only used for testing. Consequently, it is safe to use a simple
61      * random number generator, thus the sonar is disabled.
62      */
63     private static final Random RANDOM = new Random();      // NOSONAR
64
65     /**
66      * Listens for messages on the topic, decodes them into a message, and then dispatches them.
67      */
68     private final MessageTypeDispatcher msgDispatcher;
69
70     /**
71      * Used to manage the services.
72      */
73     private final ServiceManager manager;
74
75
76     @Getter
77     @Setter(lombok.AccessLevel.PRIVATE)
78     private volatile boolean alive = false;
79
80     /**
81      * Instantiate the activator for onappf PDP-A.
82      *
83      * @param pdpSimulatorParameterGroup the parameters for the onappf PDP-A service
84      */
85     public PdpSimulatorActivator(final PdpSimulatorParameterGroup pdpSimulatorParameterGroup) {
86
87         topicSinks = TopicEndpointManager.getManager()
88                         .addTopicSinks(pdpSimulatorParameterGroup.getTopicParameterGroup().getTopicSinks());
89         topicSources = TopicEndpointManager.getManager()
90                         .addTopicSources(pdpSimulatorParameterGroup.getTopicParameterGroup().getTopicSources());
91
92         final var random = RANDOM.nextInt();
93         final String instanceId = "pdp_" + random;
94         LOGGER.debug("PdpSimulatorActivator initializing with instance id: {}", instanceId);
95         try {
96             this.pdpSimulatorParameterGroup = pdpSimulatorParameterGroup;
97             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
98         } catch (final RuntimeException e) {
99             throw new PdpSimulatorRunTimeException(e);
100         }
101
102         final var pdpUpdateListener = new PdpUpdateListener();
103         final var pdpStateChangeListener = new PdpStateChangeListener();
104         // @formatter:off
105         this.manager = new ServiceManager()
106             .addAction("topics",
107                 TopicEndpointManager.getManager()::start,
108                 TopicEndpointManager.getManager()::shutdown)
109             .addAction("set alive",
110                 () -> setAlive(true),
111                 () -> setAlive(false))
112             .addAction("register pdp status context object",
113                 () -> Registry.register(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT,
114                         new PdpMessageHandler().createPdpStatusFromParameters(instanceId,
115                                 pdpSimulatorParameterGroup.getPdpStatusParameters())),
116                 () -> Registry.unregister(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT))
117             .addAction("topic sinks",
118                 () -> Registry.register(PdpSimulatorConstants.REG_PDP_TOPIC_SINKS, topicSinks),
119                 () -> Registry.unregister(PdpSimulatorConstants.REG_PDP_TOPIC_SINKS))
120             .addAction("Pdp Status publisher",
121                 () -> Registry.register(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER,
122                         new PdpStatusPublisher(topicSinks,
123                                 pdpSimulatorParameterGroup.getPdpStatusParameters().getTimeIntervalMs())),
124                 this::stopAndRemovePdpStatusPublisher)
125             .addAction("Register pdp update listener",
126                 () -> msgDispatcher.register(PdpMessageType.PDP_UPDATE.name(), pdpUpdateListener),
127                 () -> msgDispatcher.unregister(PdpMessageType.PDP_UPDATE.name()))
128             .addAction("Register pdp state change request dispatcher",
129                 () -> msgDispatcher.register(PdpMessageType.PDP_STATE_CHANGE.name(), pdpStateChangeListener),
130                 () -> msgDispatcher.unregister(PdpMessageType.PDP_STATE_CHANGE.name()))
131             .addAction("Message Dispatcher",
132                 this::registerMsgDispatcher,
133                 this::unregisterMsgDispatcher);
134
135         // @formatter:on
136     }
137
138     /**
139      * Method to stop and unregister the pdp status publisher.
140      */
141     private void stopAndRemovePdpStatusPublisher() {
142         final var pdpStatusPublisher =
143                 Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
144         pdpStatusPublisher.terminate();
145         Registry.unregister(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER);
146     }
147
148     /**
149      * Initialize PdpSimulator service.
150      *
151      * @throws PdpSimulatorException on errors in initializing the service
152      */
153     public void initialize() throws PdpSimulatorException {
154         if (isAlive()) {
155             throw new IllegalStateException("activator already initialized");
156         }
157
158         try {
159             LOGGER.debug("PdpSimulator starting as a service . . .");
160             manager.start();
161             LOGGER.debug("PdpSimulator started as a service");
162         } catch (final ServiceManagerException exp) {
163             LOGGER.error("PdpSimulator service startup failed");
164             throw new PdpSimulatorException(exp.getMessage(), exp);
165         }
166     }
167
168     /**
169      * Terminate PdpSimulator.
170      *
171      * @throws PdpSimulatorException on errors in terminating the service
172      */
173     public void terminate() throws PdpSimulatorException {
174         if (!isAlive()) {
175             throw new IllegalStateException("activator is not running");
176         }
177         try {
178             final var pdpStatusPublisher =
179                     Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
180             // send a final heartbeat with terminated status
181             pdpStatusPublisher.send(new PdpMessageHandler().getTerminatedPdpStatus());
182             manager.stop();
183             Registry.unregister(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR);
184         } catch (final ServiceManagerException exp) {
185             LOGGER.error("PdpSimulator termination failed");
186             throw new PdpSimulatorException(exp.getMessage(), exp);
187         }
188     }
189
190     /**
191      * Get the parameters used by the activator.
192      *
193      * @return pdpSimulatorParameterGroup the parameters of the activator
194      */
195     public PdpSimulatorParameterGroup getParameterGroup() {
196         return pdpSimulatorParameterGroup;
197     }
198
199     /**
200      * Registers the dispatcher with the topic source(s).
201      */
202     private void registerMsgDispatcher() {
203         for (final TopicSource source : topicSources) {
204             source.register(msgDispatcher);
205         }
206     }
207
208     /**
209      * Unregisters the dispatcher from the topic source(s).
210      */
211     private void unregisterMsgDispatcher() {
212         for (final TopicSource source : topicSources) {
213             source.unregister(msgDispatcher);
214         }
215     }
216 }