9e30c51d3a26ce6c04165de822d3a6553ae07467
[portal/nonrtric-controlpanel.git] / webapp-backend / src / main / java / org / oransc / portal / nonrtric / controlpanel / policyagentapi / PolicyAgentApiImpl.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 Nordix Foundation
6  * Modifications Copyright (C) 2020 Nordix Foundation
7  * %%
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ========================LICENSE_END===================================
20  */
21 package org.oransc.portal.nonrtric.controlpanel.policyagentapi;
22
23 import com.google.gson.GsonBuilder;
24 import com.google.gson.JsonArray;
25 import com.google.gson.JsonElement;
26 import com.google.gson.JsonObject;
27 import com.google.gson.JsonParser;
28 import com.google.gson.reflect.TypeToken;
29
30 import java.lang.invoke.MethodHandles;
31 import java.lang.reflect.Type;
32 import java.util.ArrayList;
33 import java.util.Collection;
34 import java.util.List;
35
36 import org.immutables.gson.Gson;
37 import org.immutables.value.Value;
38 import org.oransc.portal.nonrtric.controlpanel.model.PolicyInfo;
39 import org.oransc.portal.nonrtric.controlpanel.model.PolicyInstance;
40 import org.oransc.portal.nonrtric.controlpanel.model.PolicyType;
41 import org.oransc.portal.nonrtric.controlpanel.model.PolicyTypes;
42 import org.oransc.portal.nonrtric.controlpanel.util.AsyncRestClient;
43 import org.oransc.portal.nonrtric.controlpanel.util.ErrorResponseHandler;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.http.HttpStatus;
48 import org.springframework.http.ResponseEntity;
49 import org.springframework.stereotype.Component;
50
51 @Component("PolicyAgentApi")
52 public class PolicyAgentApiImpl implements PolicyAgentApi {
53     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
54
55     private final AsyncRestClient webClient;
56
57     private static com.google.gson.Gson gson = new GsonBuilder() //
58         .serializeNulls() //
59         .create(); //
60
61     @Autowired
62     public PolicyAgentApiImpl(
63         @org.springframework.beans.factory.annotation.Value("${policycontroller.url.prefix}") final String urlPrefix) {
64         this(new AsyncRestClient(urlPrefix));
65         logger.debug("ctor prefix '{}'", urlPrefix);
66     }
67
68     public PolicyAgentApiImpl(AsyncRestClient webClient) {
69         this.webClient = webClient;
70     }
71
72     @Override
73     public ResponseEntity<String> getAllPolicyTypes() {
74         try {
75             final String url = "/v2/policy-types";
76             ResponseEntity<String> rsp = webClient.getForEntity(url).block();
77             if (!rsp.getStatusCode().is2xxSuccessful()) {
78                 return rsp;
79             }
80
81             PolicyTypes result = new PolicyTypes();
82             JsonArray policyTypeIds = JsonParser.parseString(rsp.getBody()).getAsJsonObject() //
83                 .get("policytype_ids") //
84                 .getAsJsonArray(); //
85
86             for (JsonElement policyTypeId : policyTypeIds) {
87
88                 String typeId = policyTypeId.getAsString();
89
90                 JsonObject schemaObj = getIndividualPolicySchema(typeId);
91                 PolicyType pt = new PolicyType(typeId, schemaObj.toString());
92                 result.add(pt);
93             }
94             return new ResponseEntity<>(gson.toJson(result), rsp.getStatusCode());
95         } catch (Exception e) {
96             return ErrorResponseHandler.handleException(e);
97         }
98     }
99
100     public JsonObject getIndividualPolicySchema(String id) {
101         try {
102             final String url = "/v2/policy-types/" + id;
103             ResponseEntity<String> rsp = webClient.getForEntity(url).block();
104             if (!rsp.getStatusCode().is2xxSuccessful()) {
105                 return null;
106             }
107
108             JsonObject policy_schema = JsonParser.parseString(rsp.getBody()).getAsJsonObject() //
109                 .get("policy_schema") //
110                 .getAsJsonObject(); //
111
112             return policy_schema;
113         } catch (Exception e) {
114             return null;
115         }
116     }
117
118     @Override
119     public ResponseEntity<String> getPolicyInstancesForType(String type) {
120         try {
121             String url = "/v2/policies?policytype_id=" + type;
122             ResponseEntity<String> rsp = webClient.getForEntity(url).block();
123             if (!rsp.getStatusCode().is2xxSuccessful()) {
124                 return rsp;
125             }
126             JsonArray policyInstances = JsonParser.parseString(rsp.getBody()).getAsJsonObject() //
127                 .get("policy_ids") //
128                 .getAsJsonArray(); //
129
130             List<Object> res = new ArrayList<>();
131             for (JsonElement p : policyInstances) {
132                 ResponseEntity<Object> policyInstance = getIndividualPolicyInstance(p.getAsString());
133                 res.add(policyInstance.getBody());
134             }
135
136             return new ResponseEntity<>(gson.toJson(res), rsp.getStatusCode());
137         } catch (Exception e) {
138             return ErrorResponseHandler.handleException(e);
139         }
140     }
141
142     public ResponseEntity<Object> getIndividualPolicyInstance(String id) {
143         try {
144             String url = "/v2/policies/" + id;
145             ResponseEntity<String> rsp = webClient.getForEntity(url).block();
146             JsonObject obj = JsonParser.parseString(rsp.getBody()).getAsJsonObject();
147
148             // lastModified timestamp is fetched from PolicyStatus instead
149             ResponseEntity<String> status = getPolicyStatus(id);
150             String lastModified = JsonParser.parseString(status.getBody()).getAsJsonObject() //
151                 .get("last_modified") //
152                 .getAsString(); //
153             obj.addProperty("lastModified", lastModified);
154
155             PolicyInfo i = gson.fromJson(obj, PolicyInfo.class);
156             return new ResponseEntity<>(i, rsp.getStatusCode());
157         } catch (Exception e) {
158             ResponseEntity<String> rsp = ErrorResponseHandler.handleException(e);
159             return new ResponseEntity<>(rsp.getBody(), rsp.getStatusCode());
160         }
161     }
162
163     public ResponseEntity<String> getPolicyStatus(String id) {
164         try {
165             String url = "/v2/policies/" + id + "/status";
166             ResponseEntity<String> rsp = webClient.getForEntity(url).block();
167             return new ResponseEntity<>(rsp.getBody(), rsp.getStatusCode());
168         } catch (Exception e) {
169             ResponseEntity<String> rsp = ErrorResponseHandler.handleException(e);
170             return new ResponseEntity<>(rsp.getBody(), rsp.getStatusCode());
171         }
172     }
173
174     @Override
175     public ResponseEntity<Object> getPolicyInstance(String id) {
176         ResponseEntity<Object> rsp = getIndividualPolicyInstance(id);
177         PolicyInfo i = (PolicyInfo) rsp.getBody();
178         return new ResponseEntity<>(i.policyData, rsp.getStatusCode());
179     }
180
181     @Override
182     public ResponseEntity<String> putPolicy(String policyTypeIdString, String policyInstanceId, Object json,
183         String ric) {
184         String url = "/v2/policies/";
185
186         JsonElement data = JsonParser.parseString(json.toString()).getAsJsonObject();
187
188         PolicyInstance i = PolicyInstance.builder() //
189             .policyId(policyInstanceId) //
190             .policyTypeId(policyTypeIdString) //
191             .ricId(ric) //
192             .policyData(data) //
193             .serviceId("controlpanel") //
194             .build(); //
195
196         try {
197             String jsonStr = gson.toJson(i, PolicyInstance.class);
198             logger.debug("PolicyInstance: " + jsonStr);
199             webClient.putForEntity(url, jsonStr).block();
200             return new ResponseEntity<>(HttpStatus.OK);
201         } catch (Exception e) {
202             return ErrorResponseHandler.handleException(e);
203         }
204     }
205
206     @Override
207     public ResponseEntity<String> deletePolicy(String policyInstanceId) {
208         String url = "/v2/policies/" + policyInstanceId;
209         try {
210             webClient.deleteForEntity(url).block();
211             return new ResponseEntity<>(HttpStatus.OK);
212         } catch (Exception e) {
213             return ErrorResponseHandler.handleException(e);
214         }
215     }
216
217     @Value.Immutable
218     @Gson.TypeAdapters
219     interface RicInfo {
220         public String ric_id();
221
222         public Collection<String> managed_element_ids();
223
224         public Collection<String> policytype_ids();
225     }
226
227     @Override
228     public ResponseEntity<String> getRicsSupportingType(String typeName) {
229         try {
230             String url = "/v2/rics?policytype_id=" + typeName;
231             ResponseEntity<String> rsp = webClient.getForEntity(url).block();
232             if (!rsp.getStatusCode().is2xxSuccessful()) {
233                 return rsp;
234             }
235
236             JsonArray rics = JsonParser.parseString(rsp.getBody()).getAsJsonObject() //
237                 .get("rics") //
238                 .getAsJsonArray(); //
239
240             Type listType = new TypeToken<List<ImmutableRicInfo>>() {}.getType();
241             List<RicInfo> rspParsed = gson.fromJson(rics, listType);
242             Collection<String> result = new ArrayList<>(rspParsed.size());
243             for (RicInfo ric : rspParsed) {
244                 result.add(ric.ric_id());
245             }
246             String json = gson.toJson(result);
247             return new ResponseEntity<>(json, HttpStatus.OK);
248         } catch (Exception e) {
249             return ErrorResponseHandler.handleException(e);
250         }
251     }
252 }