5706a9136dee080bc3f3b5f65758d22497fcc170
[nonrtric.git] / dashboard / webapp-backend / src / test / java / org / oransc / ric / portal / dashboard / config / A1ControllerMockConfiguration.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
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 package org.oransc.ric.portal.dashboard.config;
21
22 import static org.mockito.ArgumentMatchers.any;
23 import static org.mockito.Mockito.doAnswer;
24 import static org.mockito.Mockito.mock;
25 import static org.mockito.Mockito.when;
26 import com.fasterxml.jackson.core.JsonProcessingException;
27
28 import java.io.BufferedReader;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.io.InputStreamReader;
32 import java.lang.invoke.MethodHandles;
33 import java.nio.charset.StandardCharsets;
34 import java.util.ArrayList;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Optional;
41 import java.util.Set;
42 import java.util.stream.Collectors;
43
44 import org.oransc.ric.a1controller.client.api.A1ControllerApi;
45 import org.oransc.ric.a1controller.client.invoker.ApiClient;
46 import org.oransc.ric.a1controller.client.model.InputNRRidPTidPIidPISchema;
47 import org.oransc.ric.a1controller.client.model.InputNRRidPTidPIidSchema;
48 import org.oransc.ric.a1controller.client.model.InputNRRidPTidSchema;
49 import org.oransc.ric.a1controller.client.model.InputNRRidSchema;
50 import org.oransc.ric.a1controller.client.model.OutputCodeSchema;
51 import org.oransc.ric.a1controller.client.model.OutputCodeSchemaOutput;
52 import org.oransc.ric.a1controller.client.model.OutputDescNamePTCodeSchema;
53 import org.oransc.ric.a1controller.client.model.OutputDescNamePTCodeSchemaOutput;
54 import org.oransc.ric.a1controller.client.model.OutputPICodeSchema;
55 import org.oransc.ric.a1controller.client.model.OutputPICodeSchemaOutput;
56 import org.oransc.ric.a1controller.client.model.OutputPIidsListCodeSchema;
57 import org.oransc.ric.a1controller.client.model.OutputPIidsListCodeSchemaOutput;
58 import org.oransc.ric.a1controller.client.model.OutputPTidsListCodeSchema;
59 import org.oransc.ric.a1controller.client.model.OutputPTidsListCodeSchemaOutput;
60 import org.oransc.ric.portal.dashboard.model.PolicyType;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63 import org.springframework.beans.factory.annotation.Value;
64 import org.springframework.context.annotation.Bean;
65 import org.springframework.context.annotation.Configuration;
66 import org.springframework.context.annotation.Profile;
67 import org.springframework.http.HttpStatus;
68
69 /**
70  * Creates a mock implementation of the A1 controller client API.
71  */
72 @Profile("test")
73 @Configuration
74 public class A1ControllerMockConfiguration {
75
76         private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
77
78         // A "control" is an element in the XApp descriptor
79         public static final String AC_CONTROL_NAME = "admission_control_policy";
80
81         // Simulate remote method delay for UI testing
82         @Value("${mock.config.delay:0}")
83         private int delayMs;
84
85         public A1ControllerMockConfiguration() {
86                 logger.info("Configuring mock A1 Mediator");
87         }
88
89         private ApiClient apiClient() {
90                 ApiClient mockClient = mock(ApiClient.class);
91                 when(mockClient.getStatusCode()).thenReturn(HttpStatus.OK);
92                 return mockClient;
93         }
94
95         @Bean
96         // Use the same name as regular configuration
97         public A1ControllerApi a1ControllerApi() {
98                 ApiClient apiClient = apiClient();
99                 A1ControllerApi mockApi = mock(A1ControllerApi.class);
100
101                 when(mockApi.getApiClient()).thenReturn(apiClient);
102
103                 doAnswer(inv -> {
104                         if (delayMs > 0) {
105                                 logger.debug("a1ControllerGetHandler sleeping {}", delayMs);
106                                 Thread.sleep(delayMs);
107                         }
108                         List<Integer> types = database.getTypes();
109                         OutputPTidsListCodeSchemaOutput output = new OutputPTidsListCodeSchemaOutput();
110                         output.setPolicyTypeIdList(types);
111                         output.setCode(String.valueOf(HttpStatus.OK.value()));
112                         OutputPTidsListCodeSchema outputSchema = new OutputPTidsListCodeSchema();
113                         outputSchema.setOutput(output);
114                         return outputSchema;
115                 }).when(mockApi).a1ControllerGetAllPolicyTypes(any(InputNRRidSchema.class));
116
117                 doAnswer(inv -> {
118                         if (delayMs > 0) {
119                                 logger.debug("a1ControllerGetPolicyType sleeping {}", delayMs);
120                                 Thread.sleep(delayMs);
121                         }
122                         InputNRRidPTidSchema input = inv.<InputNRRidPTidSchema>getArgument(0);
123                         PolicyType policyType = database.getPolicyType(input.getInput().getPolicyTypeId());
124                         OutputDescNamePTCodeSchemaOutput type = new OutputDescNamePTCodeSchemaOutput();
125                         type.setName(policyType.getName());
126                         type.setPolicyType(database.normalize(policyType.getSchema()));
127                         type.setCode(String.valueOf(HttpStatus.OK.value()));
128                         OutputDescNamePTCodeSchema outputSchema = new OutputDescNamePTCodeSchema();
129                         outputSchema.setOutput(type);
130                         return outputSchema;
131                 }).when(mockApi).a1ControllerGetPolicyType(any(InputNRRidPTidSchema.class));
132
133                 doAnswer(inv -> {
134                         if (delayMs > 0) {
135                                 logger.debug("a1ControllerGetHandler sleeping {}", delayMs);
136                                 Thread.sleep(delayMs);
137                         }
138                         InputNRRidPTidSchema input = inv.<InputNRRidPTidSchema>getArgument(0);
139                         List<String> instances = database.getInstances(Optional.of(input.getInput().getPolicyTypeId()));
140                         OutputPIidsListCodeSchemaOutput instancesOutput = new OutputPIidsListCodeSchemaOutput();
141                         instancesOutput.setPolicyInstanceIdList(instances);
142                         instancesOutput.setCode(String.valueOf(HttpStatus.OK.value()));
143                         OutputPIidsListCodeSchema outputSchema = new OutputPIidsListCodeSchema();
144                         outputSchema.setOutput(instancesOutput);
145                         return outputSchema;
146                 }).when(mockApi).a1ControllerGetAllInstancesForType(any(InputNRRidPTidSchema.class));
147
148                 doAnswer(inv -> {
149                         if (delayMs > 0) {
150                                 logger.debug("a1ControllerGetHandler sleeping {}", delayMs);
151                                 Thread.sleep(delayMs);
152                         }
153                         InputNRRidPTidPIidSchema input = inv.<InputNRRidPTidPIidSchema>getArgument(0);
154                         Integer polcyTypeId = input.getInput().getPolicyTypeId();
155                         String instanceId = input.getInput().getPolicyInstanceId();
156                         String instance = database.normalize(database.getInstance(polcyTypeId, instanceId));
157                         OutputPICodeSchemaOutput instanceOutput = new OutputPICodeSchemaOutput();
158                         instanceOutput.setPolicyInstance(instance);
159                         instanceOutput.setCode(String.valueOf(HttpStatus.OK.value()));
160                         OutputPICodeSchema outputSchema = new OutputPICodeSchema();
161                         outputSchema.setOutput(instanceOutput);
162                         return outputSchema;
163                 }).when(mockApi).a1ControllerGetPolicyInstance(any(InputNRRidPTidPIidSchema.class));
164
165                 doAnswer(inv -> {
166                         if (delayMs > 0) {
167                                 logger.debug("a1ControllerGetHandler sleeping {}", delayMs);
168                                 Thread.sleep(delayMs);
169                         }
170                         InputNRRidPTidPIidPISchema input = inv.<InputNRRidPTidPIidPISchema>getArgument(0);
171                         Integer polcyTypeId = input.getInput().getPolicyTypeId();
172                         String instanceId = input.getInput().getPolicyInstanceId();
173                         String instance = input.getInput().getPolicyInstance();
174                         database.putInstance(polcyTypeId, instanceId, instance);
175                         OutputCodeSchemaOutput outputCodeSchemaOutput = new OutputCodeSchemaOutput();
176                         outputCodeSchemaOutput.setCode(String.valueOf(HttpStatus.CREATED.value()));
177                         OutputCodeSchema outputCodeSchema = new OutputCodeSchema();
178                         outputCodeSchema.setOutput(outputCodeSchemaOutput);
179                         return outputCodeSchema;
180                 }).when(mockApi).a1ControllerCreatePolicyInstance(any(InputNRRidPTidPIidPISchema.class));
181
182                 doAnswer(inv -> {
183                         if (delayMs > 0) {
184                                 logger.debug("a1ControllerGetHandler sleeping {}", delayMs);
185                                 Thread.sleep(delayMs);
186                         }
187                         InputNRRidPTidPIidSchema input = inv.<InputNRRidPTidPIidSchema>getArgument(0);
188                         Integer polcyTypeId = input.getInput().getPolicyTypeId();
189                         String instanceId = input.getInput().getPolicyInstanceId();
190                         database.deleteInstance(polcyTypeId, instanceId);
191                         OutputCodeSchemaOutput outputCodeSchemaOutput = new OutputCodeSchemaOutput();
192                         outputCodeSchemaOutput.setCode(String.valueOf(HttpStatus.NO_CONTENT.value()));
193                         OutputCodeSchema outputCodeSchema = new OutputCodeSchema();
194                         outputCodeSchema.setOutput(outputCodeSchemaOutput);
195                         return outputCodeSchema;
196                 }).when(mockApi).a1ControllerDeletePolicyInstance(any(InputNRRidPTidPIidSchema.class));
197
198                 return mockApi;
199         }
200
201         class Database {
202
203                 public class PolicyException extends Exception {
204
205                         private static final long serialVersionUID = 1L;
206
207                         public PolicyException(String message) {
208                                 super(message);
209                                 System.out.println("**** Exception " + message);
210                         }
211                 }
212
213                 private class PolicyTypeHolder {
214                         PolicyTypeHolder(PolicyType pt) {
215                                 this.policyType = pt;
216                         }
217
218                         String getInstance(String instanceId) throws PolicyException {
219                                 String instance = instances.get(instanceId);
220                                 if (instance == null) {
221                                         throw new PolicyException("Instance not found: " + instanceId);
222                                 }
223                                 return instance;
224                         }
225
226                         PolicyType getPolicyType() {
227                                 return policyType;
228                         }
229
230                         void putInstance(String id, String data) {
231                                 instances.put(id, data);
232                         }
233
234                         void deleteInstance(String id) {
235                                 instances.remove(id);
236                         }
237
238                         List<String> getInstances() {
239                                 return new ArrayList<>(instances.keySet());
240                         }
241
242                         private final PolicyType policyType;
243                         private Map<String, String> instances = new HashMap<>();
244                 }
245
246                 Database() {
247                         String schema = getStringFromFile("anr-policy-schema.json");
248                         PolicyType policy = new PolicyType(1, "ANR", schema);
249                         types.put(1, new PolicyTypeHolder(policy));
250
251                         schema = getStringFromFile("demo-policy-schema-1.json");
252                         policy = new PolicyType(2, "type2", schema);
253                         types.put(2, new PolicyTypeHolder(policy));
254
255                         schema = getStringFromFile("demo-policy-schema-2.json");
256                         policy = new PolicyType(3, "type3", schema);
257                         types.put(3, new PolicyTypeHolder(policy));
258
259                         schema = getStringFromFile("demo-policy-schema-3.json");
260                         policy = new PolicyType(4, "type4", schema);
261                         types.put(4, new PolicyTypeHolder(policy));
262                         try {
263                                 putInstance(1, "ANR-1", getStringFromFile("anr-policy-instance.json"));
264                         } catch (JsonProcessingException | PolicyException e) {
265                                 // Nothing
266                         }
267                 }
268
269                 private String getStringFromFile(String path) {
270                         try {
271                                 InputStream inputStream = MethodHandles.lookup().lookupClass().getClassLoader()
272                                                 .getResourceAsStream(path);
273                                 return new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining("\n"));
274                         } catch (Exception e) {
275                                 logger.error("Cannot read file :" + path, e);
276                                 return "";
277                         }
278                 }
279
280                 String normalize(String str) {
281                         return str.replace('\n', ' ');
282                 }
283
284                 void putInstance(Integer typeId, String instanceId, String instanceData)
285                                 throws JsonProcessingException, PolicyException {
286                         PolicyTypeHolder type = getTypeHolder(typeId);
287                         type.putInstance(instanceId, instanceData);
288                 }
289
290                 void deleteInstance(Integer typeId, String instanceId) throws JsonProcessingException, PolicyException {
291                         PolicyTypeHolder type = getTypeHolder(typeId);
292                         type.deleteInstance(instanceId);
293                 }
294
295                 String getInstance(Integer typeId, String instanceId) throws JsonProcessingException, PolicyException {
296                         return getTypeHolder(typeId).getInstance(instanceId);
297                 }
298
299                 List<Integer> getTypes() {
300                         return new ArrayList<>(types.keySet());
301                 }
302
303                 List<String> getInstances(Optional<Integer> typeId) throws PolicyException {
304                         if (typeId.isPresent()) {
305                                 return getTypeHolder(typeId.get()).getInstances();
306                         } else {
307                                 Set<String> res = new HashSet<String>();
308                                 for (Iterator<PolicyTypeHolder> i = types.values().iterator(); i.hasNext();) {
309                                         res.addAll(i.next().getInstances());
310                                 }
311                                 return new ArrayList<>(res);
312                         }
313                 }
314
315                 private PolicyTypeHolder getTypeHolder(Integer typeId) throws PolicyException {
316                         PolicyTypeHolder typeHolder = types.get(typeId);
317                         if (typeHolder == null) {
318                                 throw new PolicyException("Type not found: " + typeId);
319                         }
320                         return typeHolder;
321                 }
322
323                 private PolicyType getPolicyType(Integer typeId) throws PolicyException {
324                         PolicyTypeHolder typeHolder = getTypeHolder(typeId);
325                         return typeHolder.getPolicyType();
326                 }
327
328                 private Map<Integer, PolicyTypeHolder> types = new HashMap<>();
329
330         }
331
332         private final Database database = new Database();
333 }