2268fe06dcd15b1574f65ad9735b7d3ce5293d3d
[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("demo-policy-schema-1.json");
119             PolicyType policyType = new PolicyType("type2", schema);
120             types.put("type2", policyType);
121
122             schema = getStringFromFile("demo-policy-schema-2.json");
123             policyType = new PolicyType("type3", schema);
124             types.put("type3", policyType);
125
126             schema = getStringFromFile("demo-policy-schema-3.json");
127             policyType = new PolicyType("type4", schema);
128             types.put("type4", policyType);
129         }
130
131         private String getStringFromFile(String path) {
132             try {
133                 InputStream inputStream = MethodHandles.lookup().lookupClass().getClassLoader()
134                         .getResourceAsStream(path);
135                 return new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining("\n"));
136             } catch (Exception e) {
137                 logger.error("Cannot read file :" + path, e);
138                 return "";
139             }
140         }
141
142         String normalize(String str) {
143             return str.replace('\n', ' ');
144         }
145
146         private String getTimeStampUTC() {
147             return java.time.Instant.now().toString();
148         }
149
150         void putInstance(String typeId, String instanceId, String instanceData, String ric) {
151             PolicyInfo i = ImmutablePolicyInfo.builder().json(instanceData).lastModified(getTimeStampUTC())
152                     .id(instanceId).ric(ric).service("service").type(typeId).build();
153             instances.put(instanceId, i);
154         }
155
156         public void deleteInstance(String instanceId) {
157             instances.remove(instanceId);
158         }
159
160         String getInstance(String id) throws RestClientException {
161             PolicyInfo i = instances.get(id);
162             if (i == null) {
163                 throw new RestClientException("Type not found: " + id);
164             }
165             return i.json();
166         }
167
168         public Collection<PolicyType> getTypes() {
169             return types.values();
170         }
171
172         public List<PolicyInfo> getInstances(Optional<String> typeId) {
173             ArrayList<PolicyInfo> result = new ArrayList<>();
174             for (PolicyInfo i : instances.values()) {
175                 if (typeId.isPresent()) {
176                     if (i.type().equals(typeId.get())) {
177                         result.add(i);
178                     }
179
180                 } else {
181                     result.add(i);
182                 }
183             }
184             return result;
185         }
186
187         private Map<String, PolicyType> types = new HashMap<>();
188         private Map<String, PolicyInfo> instances = new HashMap<>();
189
190     }
191
192 }