Return response codes from policy controller
[nonrtric.git] / dashboard / webapp-backend / src / test / java / org / oransc / ric / portal / dashboard / config / PolicyControllerMockConfiguration.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 com.google.gson.GsonBuilder;
23
24 import java.io.BufferedReader;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.lang.invoke.MethodHandles;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Optional;
34 import java.util.Vector;
35 import java.util.stream.Collectors;
36
37 import org.oransc.ric.portal.dashboard.model.ImmutablePolicyInfo;
38 import org.oransc.ric.portal.dashboard.model.PolicyInfo;
39 import org.oransc.ric.portal.dashboard.model.PolicyInstances;
40 import org.oransc.ric.portal.dashboard.model.PolicyType;
41 import org.oransc.ric.portal.dashboard.model.PolicyTypes;
42 import org.oransc.ric.portal.dashboard.policyagentapi.PolicyAgentApi;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.springframework.boot.test.context.TestConfiguration;
46 import org.springframework.context.annotation.Bean;
47 import org.springframework.http.HttpStatus;
48 import org.springframework.http.ResponseEntity;
49 import org.springframework.web.client.RestClientException;
50
51 /**
52  * Creates a mock implementation of the policy controller client API.
53  */
54 @TestConfiguration
55 public class PolicyControllerMockConfiguration {
56
57     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
58
59     private static com.google.gson.Gson gson = new GsonBuilder() //
60         .serializeNulls() //
61         .create(); //
62
63     @Bean
64     public PolicyAgentApi policyAgentApi() {
65         MockPolicyAgentApi apiClient = new MockPolicyAgentApi();
66         return apiClient;
67     }
68
69     class MockPolicyAgentApi implements PolicyAgentApi {
70         private final Database database = new Database();
71
72         @Override
73         public ResponseEntity<String> getPolicyInstance(String id) {
74             return new ResponseEntity<>(database.getInstance(id), HttpStatus.OK);
75         }
76
77         @Override
78         public ResponseEntity<String> putPolicy(String policyTypeIdString, String policyInstanceId, String json,
79             String ric) {
80             database.putInstance(policyTypeIdString, policyInstanceId, json, ric);
81             return new ResponseEntity<>("Policy was put successfully", HttpStatus.OK);
82         }
83
84         @Override
85         public ResponseEntity<String> deletePolicy(String policyInstanceId) {
86             database.deleteInstance(policyInstanceId);
87             return new ResponseEntity<>("Policy was deleted successfully", HttpStatus.NO_CONTENT);
88         }
89
90         @Override
91         public ResponseEntity<String> getAllPolicyTypes() {
92             PolicyTypes result = new PolicyTypes();
93             result.addAll(database.getTypes());
94             return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
95         }
96
97         @Override
98         public ResponseEntity<String> getPolicyInstancesForType(String type) {
99             PolicyInstances result = new PolicyInstances();
100             List<PolicyInfo> inst = database.getInstances(Optional.of(type));
101             result.addAll(inst);
102             return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
103         }
104
105         @Override
106         public ResponseEntity<String> getRicsSupportingType(String typeName) {
107             Vector<String> res = new Vector<>();
108             res.add("ric_1");
109             res.add("ric_2");
110             res.add("ric_3");
111             return new ResponseEntity<>(gson.toJson(res), HttpStatus.OK);
112         }
113     }
114
115     class Database {
116
117         Database() {
118             String schema = getStringFromFile("anr-policy-schema.json");
119             PolicyType policy = new PolicyType("ANR", schema);
120             types.put("ANR", policy);
121
122             schema = getStringFromFile("demo-policy-schema-1.json");
123             policy = new PolicyType("type2", schema);
124             types.put("type2", policy);
125
126             schema = getStringFromFile("demo-policy-schema-2.json");
127             policy = new PolicyType("type3", schema);
128             types.put("type3", policy);
129
130             schema = getStringFromFile("demo-policy-schema-3.json");
131             policy = new PolicyType("type4", schema);
132             types.put("type4", policy);
133             try {
134                 putInstance("ANR", "ANR-1", getStringFromFile("anr-policy-instance.json"), "ric_1");
135             } catch (Exception e) {
136                 // Nothing
137             }
138         }
139
140         private String getStringFromFile(String path) {
141             try {
142                 InputStream inputStream =
143                     MethodHandles.lookup().lookupClass().getClassLoader().getResourceAsStream(path);
144                 return new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining("\n"));
145             } catch (Exception e) {
146                 logger.error("Cannot read file :" + path, e);
147                 return "";
148             }
149         }
150
151         String normalize(String str) {
152             return str.replace('\n', ' ');
153         }
154
155         private String getTimeStampUTC() {
156             return java.time.Instant.now().toString();
157         }
158
159         void putInstance(String typeId, String instanceId, String instanceData, String ric) {
160             PolicyInfo i = ImmutablePolicyInfo.builder().json(instanceData).lastModified(getTimeStampUTC())
161                 .id(instanceId).ric(ric).service("service").type(typeId).build();
162             instances.put(instanceId, i);
163         }
164
165         public void deleteInstance(String instanceId) {
166             instances.remove(instanceId);
167         }
168
169         String getInstance(String id) throws RestClientException {
170             PolicyInfo i = instances.get(id);
171             if (i == null) {
172                 throw new RestClientException("Type not found: " + id);
173             }
174             return i.json();
175         }
176
177         public Collection<PolicyType> getTypes() {
178             return types.values();
179         }
180
181         public List<PolicyInfo> getInstances(Optional<String> typeId) {
182             ArrayList<PolicyInfo> result = new ArrayList<>();
183             for (PolicyInfo i : instances.values()) {
184                 if (typeId.isPresent()) {
185                     if (i.type().equals(typeId.get())) {
186                         result.add(i);
187                     }
188
189                 } else {
190                     result.add(i);
191                 }
192             }
193             return result;
194         }
195
196         private Map<String, PolicyType> types = new HashMap<>();
197         private Map<String, PolicyInfo> instances = new HashMap<>();
198
199     }
200
201 }