f8b7c3ea9606d0c62e818ac7b1cbb79ada21d1b1
[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.ImmutablePolicyInfo;
39 import org.oransc.portal.nonrtric.controlpanel.model.PolicyInfo;
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             Type listType = new TypeToken<List<ImmutablePolicyInfo>>() {}.getType();
131             List<PolicyInfo> rspParsed = gson.fromJson(policyInstances, listType);
132
133             return new ResponseEntity<>(gson.toJson(rspParsed), rsp.getStatusCode());
134         } catch (Exception e) {
135             return ErrorResponseHandler.handleException(e);
136         }
137     }
138
139     @Override
140     public ResponseEntity<Object> getPolicyInstance(String id) {
141         try {
142             String url = "/v2/policies/" + id;
143             ResponseEntity<String> rsp = webClient.getForEntity(url).block();
144             JsonObject obj = JsonParser.parseString(rsp.getBody()).getAsJsonObject();
145             String str = obj.toString();
146             return new ResponseEntity<>(str, rsp.getStatusCode());
147         } catch (Exception e) {
148             ResponseEntity<String> rsp = ErrorResponseHandler.handleException(e);
149             return new ResponseEntity<>(rsp.getBody(), rsp.getStatusCode());
150         }
151     }
152
153     private String getTimeStampUTC() {
154         return java.time.Instant.now().toString();
155     }
156
157     @Override
158     public ResponseEntity<String> putPolicy(String policyTypeIdString, String policyInstanceId, Object json,
159         String ric) {
160         String url = "/v2/policies/";
161
162         PolicyInfo i = ImmutablePolicyInfo.builder() //
163             .id(policyInstanceId) //
164             .type(policyTypeIdString) //
165             .ric(ric) //
166             .json(json) //
167             .service("controlpanel") //
168             .lastModified(getTimeStampUTC()) //
169             .build(); //
170
171         try {
172             String jsonStr = gson.toJson(i, PolicyInfo.class);
173             webClient.putForEntity(url, jsonStr).block();
174             return new ResponseEntity<>(HttpStatus.OK);
175         } catch (Exception e) {
176             return ErrorResponseHandler.handleException(e);
177         }
178     }
179
180     @Override
181     public ResponseEntity<String> deletePolicy(String policyInstanceId) {
182         String url = "/v2/policies/" + policyInstanceId;
183         try {
184             webClient.deleteForEntity(url).block();
185             return new ResponseEntity<>(HttpStatus.OK);
186         } catch (Exception e) {
187             return ErrorResponseHandler.handleException(e);
188         }
189     }
190
191     @Value.Immutable
192     @Gson.TypeAdapters
193     interface RicInfo {
194         public String ricName();
195
196         public Collection<String> nodeNames();
197
198         public Collection<String> policyTypes();
199     }
200
201     @Override
202     public ResponseEntity<String> getRicsSupportingType(String typeName) {
203         try {
204             String url = "/v2/rics?policytype_id=" + typeName;
205             ResponseEntity<String> rsp = webClient.getForEntity(url).block();
206             if (!rsp.getStatusCode().is2xxSuccessful()) {
207                 return rsp;
208             }
209
210             JsonArray rics = JsonParser.parseString(rsp.getBody()).getAsJsonObject() //
211                 .get("rics") //
212                 .getAsJsonArray(); //
213
214             Type listType = new TypeToken<List<ImmutableRicInfo>>() {}.getType();
215             List<RicInfo> rspParsed = gson.fromJson(rics, listType);
216             Collection<String> result = new ArrayList<>(rspParsed.size());
217             for (RicInfo ric : rspParsed) {
218                 result.add(ric.ricName());
219             }
220             String json = gson.toJson(result);
221             return new ResponseEntity<>(json, HttpStatus.OK);
222         } catch (Exception e) {
223             return ErrorResponseHandler.handleException(e);
224         }
225     }
226 }