Merge "Change payload to Map<String,Object> so it's more versatile"
[policy/models.git] / models-interactions / model-actors / actor.test / src / main / java / org / onap / policy / controlloop / actor / test / BasicActor.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controlloop.actor.test;
22
23 import static org.junit.Assert.assertFalse;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26
27 import java.io.FileNotFoundException;
28 import java.util.Map;
29 import lombok.Getter;
30 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
31 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
32 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
33 import org.onap.policy.common.endpoints.http.client.HttpClientFactory;
34 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
35 import org.onap.policy.common.endpoints.parameters.TopicParameterGroup;
36 import org.onap.policy.common.parameters.BeanValidationResult;
37 import org.onap.policy.common.parameters.BeanValidator;
38 import org.onap.policy.common.parameters.annotations.NotNull;
39 import org.onap.policy.common.utils.coder.Coder;
40 import org.onap.policy.common.utils.coder.CoderException;
41 import org.onap.policy.common.utils.coder.StandardYamlCoder;
42 import org.onap.policy.common.utils.resources.ResourceUtils;
43 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
44 import org.onap.policy.controlloop.actorserviceprovider.Operator;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * Superclass for various Actor tests.
50  */
51 public class BasicActor {
52     private static final Logger logger = LoggerFactory.getLogger(BasicActor.class);
53     private static final Coder yamlCoder = new StandardYamlCoder();
54
55     /**
56      * Reads a YAML configuration file, configures the specified topics and HTTP clients,
57      * and then runs the specified actor through its paces: configure(), start(), stop(),
58      * and shutdown(). Finally, it destroys the topics and HTTP clients.
59      *
60      * @param actorName name of the actor to be tested.
61      * @param yamlConfigFile YAML configuration file name
62      * @throws IllegalArgumentException if an error occurs
63      */
64     protected void verifyActorService(String actorName, String yamlConfigFile) {
65         ActorService service = new ActorService() {};
66
67         // ensure the actor was loaded
68         assertNotNull(service.getActor(actorName));
69
70         try {
71             MyConfig config = readConfig(yamlConfigFile);
72             config.validate();
73
74             startOtherServices(config);
75
76             // configure and verify
77             service.configure(config.getActors());
78             for (Operator operator : service.getActor(actorName).getOperators()) {
79                 assertTrue(operator.isConfigured());
80             }
81
82             // start and verify
83             service.start();
84             for (Operator operator : service.getActor(actorName).getOperators()) {
85                 assertTrue(operator.isAlive());
86             }
87
88             // stop and verify
89             service.stop();
90             for (Operator operator : service.getActor(actorName).getOperators()) {
91                 assertFalse(operator.isAlive());
92             }
93
94             // shut down and verify
95             service.shutdown();
96             for (Operator operator : service.getActor(actorName).getOperators()) {
97                 assertFalse(operator.isAlive());
98             }
99
100         } catch (HttpClientConfigException e) {
101             logger.error("failed to configure HTTP client(s) for actor: {}", actorName);
102             throw new IllegalArgumentException(e);
103
104         } finally {
105             stopOtherServices();
106         }
107     }
108
109     /**
110      * Reads a YAML configuration from a file.
111      *
112      * @param yamlConfigFile YAML configuration file name
113      * @return the configuration that was read from the file
114      * @throws AssertionError if an error occurs
115      * @throws CoderException if an error occurs
116      */
117     private MyConfig readConfig(String yamlConfigFile) {
118         try {
119             String yaml = ResourceUtils.getResourceAsString(yamlConfigFile);
120             if (yaml == null) {
121                 throw new FileNotFoundException(yamlConfigFile);
122             }
123
124             return yamlCoder.decode(yaml, MyConfig.class);
125
126         } catch (CoderException | FileNotFoundException e) {
127             logger.error("cannot decode YAML file {}", yamlConfigFile);
128             throw new IllegalArgumentException(e);
129         }
130     }
131
132     /**
133      * Starts the Topic and HTTP clients.
134      *
135      * @param config configuration
136      * @throws HttpClientConfigException if an error occurs
137      */
138     private void startOtherServices(MyConfig config) throws HttpClientConfigException {
139         stopOtherServices();
140
141         if (config.getHttpClients() != null) {
142             HttpClientFactory factory = HttpClientFactoryInstance.getClientFactory();
143             for (BusTopicParams params : config.getHttpClients()) {
144                 factory.build(params);
145             }
146         }
147
148         if (config.getTopics() != null) {
149             TopicEndpointManager.getManager().addTopics(config.getTopics());
150         }
151     }
152
153     /**
154      * Stops the Topic and HTTP clients.
155      */
156     private void stopOtherServices() {
157         TopicEndpointManager.getManager().shutdown();
158         HttpClientFactoryInstance.getClientFactory().destroy();
159     }
160
161     @Getter
162     public static class MyConfig {
163         private BusTopicParams[] httpClients;
164         private TopicParameterGroup topics;
165
166         @NotNull
167         private Map<String, Map<String, Object>> actors;
168
169         /**
170          * Validates the config.
171          */
172         public void validate() {
173             BeanValidationResult result = new BeanValidator().validateTop(BasicActor.class.getSimpleName(), this);
174             if (topics != null) {
175                 result.addResult(topics.validate());
176             }
177             if (!result.isValid()) {
178                 throw new IllegalArgumentException(result.getResult());
179             }
180         }
181     }
182 }