8d72910516f3012fa2b86d7af9d4eb1149560d84
[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-2021 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.HttpClientFactoryInstance;
34 import org.onap.policy.common.endpoints.parameters.TopicParameterGroup;
35 import org.onap.policy.common.parameters.BeanValidationResult;
36 import org.onap.policy.common.parameters.BeanValidator;
37 import org.onap.policy.common.parameters.annotations.NotNull;
38 import org.onap.policy.common.utils.coder.Coder;
39 import org.onap.policy.common.utils.coder.CoderException;
40 import org.onap.policy.common.utils.coder.StandardYamlCoder;
41 import org.onap.policy.common.utils.resources.ResourceUtils;
42 import org.onap.policy.controlloop.actorserviceprovider.ActorService;
43 import org.onap.policy.controlloop.actorserviceprovider.Operator;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Superclass for various Actor tests.
49  */
50 public class BasicActor {
51     private static final Logger logger = LoggerFactory.getLogger(BasicActor.class);
52     private static final Coder yamlCoder = new StandardYamlCoder();
53
54     /**
55      * Reads a YAML configuration file, configures the specified topics and HTTP clients,
56      * and then runs the specified actor through its paces: configure(), start(), stop(),
57      * and shutdown(). Finally, it destroys the topics and HTTP clients.
58      *
59      * @param actorName name of the actor to be tested.
60      * @param yamlConfigFile YAML configuration file name
61      * @throws IllegalArgumentException if an error occurs
62      */
63     protected void verifyActorService(String actorName, String yamlConfigFile) {
64         ActorService service = new ActorService() {};
65
66         // ensure the actor was loaded
67         assertNotNull(service.getActor(actorName));
68
69         try {
70             MyConfig config = readConfig(yamlConfigFile);
71             config.validate();
72
73             startOtherServices(config);
74
75             // configure and verify
76             service.configure(config.getActors());
77             for (Operator operator : service.getActor(actorName).getOperators()) {
78                 assertTrue(operator.isConfigured());
79             }
80
81             // start and verify
82             service.start();
83             for (Operator operator : service.getActor(actorName).getOperators()) {
84                 assertTrue(operator.isAlive());
85             }
86
87             // stop and verify
88             service.stop();
89             for (Operator operator : service.getActor(actorName).getOperators()) {
90                 assertFalse(operator.isAlive());
91             }
92
93             // shut down and verify
94             service.shutdown();
95             for (Operator operator : service.getActor(actorName).getOperators()) {
96                 assertFalse(operator.isAlive());
97             }
98
99         } catch (HttpClientConfigException e) {
100             logger.error("failed to configure HTTP client(s) for actor: {}", actorName);
101             throw new IllegalArgumentException(e);
102
103         } finally {
104             stopOtherServices();
105         }
106     }
107
108     /**
109      * Reads a YAML configuration from a file.
110      *
111      * @param yamlConfigFile YAML configuration file name
112      * @return the configuration that was read from the file
113      * @throws AssertionError if an error occurs
114      */
115     private MyConfig readConfig(String yamlConfigFile) {
116         try {
117             var yaml = ResourceUtils.getResourceAsString(yamlConfigFile);
118             if (yaml == null) {
119                 throw new FileNotFoundException(yamlConfigFile);
120             }
121
122             return yamlCoder.decode(yaml, MyConfig.class);
123
124         } catch (CoderException | FileNotFoundException e) {
125             logger.error("cannot decode YAML file {}", yamlConfigFile);
126             throw new IllegalArgumentException(e);
127         }
128     }
129
130     /**
131      * Starts the Topic and HTTP clients.
132      *
133      * @param config configuration
134      * @throws HttpClientConfigException if an error occurs
135      */
136     private void startOtherServices(MyConfig config) throws HttpClientConfigException {
137         stopOtherServices();
138
139         if (config.getHttpClients() != null) {
140             var factory = HttpClientFactoryInstance.getClientFactory();
141             for (BusTopicParams params : config.getHttpClients()) {
142                 factory.build(params);
143             }
144         }
145
146         if (config.getTopics() != null) {
147             TopicEndpointManager.getManager().addTopics(config.getTopics());
148         }
149     }
150
151     /**
152      * Stops the Topic and HTTP clients.
153      */
154     private void stopOtherServices() {
155         TopicEndpointManager.getManager().shutdown();
156         HttpClientFactoryInstance.getClientFactory().destroy();
157     }
158
159     @Getter
160     public static class MyConfig {
161         private BusTopicParams[] httpClients;
162         private TopicParameterGroup topics;
163
164         @NotNull
165         private Map<String, Object> actors;
166
167         /**
168          * Validates the config.
169          */
170         public void validate() {
171             BeanValidationResult result = new BeanValidator().validateTop(BasicActor.class.getSimpleName(), this);
172             if (topics != null) {
173                 result.addResult(topics.validate());
174             }
175             if (!result.isValid()) {
176                 throw new IllegalArgumentException(result.getResult());
177             }
178         }
179     }
180 }