Fix models due to sonar changes in common
[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 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.Properties;
26 import java.util.Random;
27 import lombok.Getter;
28 import lombok.Setter;
29 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
30 import org.onap.policy.common.endpoints.event.comm.TopicSink;
31 import org.onap.policy.common.endpoints.event.comm.TopicSource;
32 import org.onap.policy.common.endpoints.listeners.MessageTypeDispatcher;
33 import org.onap.policy.common.utils.services.Registry;
34 import org.onap.policy.common.utils.services.ServiceManager;
35 import org.onap.policy.common.utils.services.ServiceManagerException;
36 import org.onap.policy.models.pdp.enums.PdpMessageType;
37 import org.onap.policy.models.sim.pdp.comm.PdpStateChangeListener;
38 import org.onap.policy.models.sim.pdp.comm.PdpStatusPublisher;
39 import org.onap.policy.models.sim.pdp.comm.PdpUpdateListener;
40 import org.onap.policy.models.sim.pdp.exception.PdpSimulatorException;
41 import org.onap.policy.models.sim.pdp.exception.PdpSimulatorRunTimeException;
42 import org.onap.policy.models.sim.pdp.handler.PdpMessageHandler;
43 import org.onap.policy.models.sim.pdp.parameters.PdpSimulatorParameterGroup;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * This class activates the PdpSimulator as a complete service together with all its handlers.
49  *
50  * @author Ajith Sreekumar (ajith.sreekumar@est.tech)
51  */
52 public class PdpSimulatorActivator {
53
54     private static final Logger LOGGER = LoggerFactory.getLogger(PdpSimulatorActivator.class);
55     private final PdpSimulatorParameterGroup pdpSimulatorParameterGroup;
56     private List<TopicSink> topicSinks;// topics to which pdp sends pdp status
57     private List<TopicSource> topicSources; // topics to which pdp listens to for messages from pap.
58     private static final String[] MSG_TYPE_NAMES = { "messageName" };
59     private static final Random RANDOM = new Random();
60
61     /**
62      * Listens for messages on the topic, decodes them into a message, and then dispatches them.
63      */
64     private final MessageTypeDispatcher msgDispatcher;
65
66     /**
67      * Used to manage the services.
68      */
69     private ServiceManager manager;
70
71
72     @Getter
73     @Setter(lombok.AccessLevel.PRIVATE)
74     private volatile boolean alive = false;
75
76     /**
77      * Instantiate the activator for onappf PDP-A.
78      *
79      * @param pdpSimulatorParameterGroup the parameters for the onappf PDP-A service
80      * @param topicProperties properties used to configure the topics
81      */
82     public PdpSimulatorActivator(final PdpSimulatorParameterGroup pdpSimulatorParameterGroup,
83             final Properties topicProperties) {
84
85         topicSinks = TopicEndpointManager.getManager().addTopicSinks(topicProperties);
86         topicSources = TopicEndpointManager.getManager().addTopicSources(topicProperties);
87
88         final int random = RANDOM.nextInt();
89         final String instanceId = "pdp_" + random;
90         LOGGER.debug("PdpSimulatorActivator initializing with instance id: {}", instanceId);
91         try {
92             this.pdpSimulatorParameterGroup = pdpSimulatorParameterGroup;
93             this.msgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES);
94         } catch (final RuntimeException e) {
95             throw new PdpSimulatorRunTimeException(e);
96         }
97
98         final PdpUpdateListener pdpUpdateListener = new PdpUpdateListener();
99         final PdpStateChangeListener pdpStateChangeListener = new PdpStateChangeListener();
100         // @formatter:off
101         this.manager = new ServiceManager()
102             .addAction("topics",
103                 TopicEndpointManager.getManager()::start,
104                 TopicEndpointManager.getManager()::shutdown)
105             .addAction("set alive",
106                 () -> setAlive(true),
107                 () -> setAlive(false))
108             .addAction("register pdp status context object",
109                 () -> Registry.register(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT,
110                         new PdpMessageHandler().createPdpStatusFromParameters(instanceId,
111                                 pdpSimulatorParameterGroup.getPdpStatusParameters())),
112                 () -> Registry.unregister(PdpSimulatorConstants.REG_PDP_STATUS_OBJECT))
113             .addAction("topic sinks",
114                 () -> Registry.register(PdpSimulatorConstants.REG_PDP_TOPIC_SINKS, topicSinks),
115                 () -> Registry.unregister(PdpSimulatorConstants.REG_PDP_TOPIC_SINKS))
116             .addAction("Pdp Status publisher",
117                 () -> Registry.register(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER,
118                         new PdpStatusPublisher(topicSinks,
119                                 pdpSimulatorParameterGroup.getPdpStatusParameters().getTimeIntervalMs())),
120                 this::stopAndRemovePdpStatusPublisher)
121             .addAction("Register pdp update listener",
122                 () -> msgDispatcher.register(PdpMessageType.PDP_UPDATE.name(), pdpUpdateListener),
123                 () -> msgDispatcher.unregister(PdpMessageType.PDP_UPDATE.name()))
124             .addAction("Register pdp state change request dispatcher",
125                 () -> msgDispatcher.register(PdpMessageType.PDP_STATE_CHANGE.name(), pdpStateChangeListener),
126                 () -> msgDispatcher.unregister(PdpMessageType.PDP_STATE_CHANGE.name()))
127             .addAction("Message Dispatcher",
128                 this::registerMsgDispatcher,
129                 this::unregisterMsgDispatcher);
130
131         // @formatter:on
132     }
133
134     /**
135      * Method to stop and unregister the pdp status publisher.
136      */
137     private void stopAndRemovePdpStatusPublisher() {
138         final PdpStatusPublisher pdpStatusPublisher =
139                 Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
140         pdpStatusPublisher.terminate();
141         Registry.unregister(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER);
142     }
143
144     /**
145      * Initialize PdpSimulator service.
146      *
147      * @throws PdpSimulatorException on errors in initializing the service
148      */
149     public void initialize() throws PdpSimulatorException {
150         if (isAlive()) {
151             throw new IllegalStateException("activator already initialized");
152         }
153
154         try {
155             LOGGER.debug("PdpSimulator starting as a service . . .");
156             manager.start();
157             LOGGER.debug("PdpSimulator started as a service");
158         } catch (final ServiceManagerException exp) {
159             LOGGER.error("PdpSimulator service startup failed");
160             throw new PdpSimulatorException(exp.getMessage(), exp);
161         }
162     }
163
164     /**
165      * Terminate PdpSimulator.
166      *
167      * @throws PdpSimulatorException on errors in terminating the service
168      */
169     public void terminate() throws PdpSimulatorException {
170         if (!isAlive()) {
171             throw new IllegalStateException("activator is not running");
172         }
173         try {
174             final PdpStatusPublisher pdpStatusPublisher =
175                     Registry.get(PdpSimulatorConstants.REG_PDP_STATUS_PUBLISHER, PdpStatusPublisher.class);
176             // send a final heartbeat with terminated status
177             pdpStatusPublisher.send(new PdpMessageHandler().getTerminatedPdpStatus());
178             manager.stop();
179             Registry.unregister(PdpSimulatorConstants.REG_PDP_SIMULATOR_ACTIVATOR);
180         } catch (final ServiceManagerException exp) {
181             LOGGER.error("PdpSimulator termination failed");
182             throw new PdpSimulatorException(exp.getMessage(), exp);
183         }
184     }
185
186     /**
187      * Get the parameters used by the activator.
188      *
189      * @return pdpSimulatorParameterGroup the parameters of the activator
190      */
191     public PdpSimulatorParameterGroup getParameterGroup() {
192         return pdpSimulatorParameterGroup;
193     }
194
195     /**
196      * Registers the dispatcher with the topic source(s).
197      */
198     private void registerMsgDispatcher() {
199         for (final TopicSource source : topicSources) {
200             source.register(msgDispatcher);
201         }
202     }
203
204     /**
205      * Unregisters the dispatcher from the topic source(s).
206      */
207     private void unregisterMsgDispatcher() {
208         for (final TopicSource source : topicSources) {
209             source.unregister(msgDispatcher);
210         }
211     }
212 }