Bugfix, handling of empty types
[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 import java.util.Map;
36
37 import org.immutables.gson.Gson;
38 import org.immutables.value.Value;
39 import org.oransc.portal.nonrtric.controlpanel.model.ImmutablePolicyInfo;
40 import org.oransc.portal.nonrtric.controlpanel.model.PolicyInfo;
41 import org.oransc.portal.nonrtric.controlpanel.model.PolicyInstances;
42 import org.oransc.portal.nonrtric.controlpanel.model.PolicyType;
43 import org.oransc.portal.nonrtric.controlpanel.model.PolicyTypes;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.http.HttpEntity;
48 import org.springframework.http.HttpHeaders;
49 import org.springframework.http.HttpStatus;
50 import org.springframework.http.MediaType;
51 import org.springframework.http.ResponseEntity;
52 import org.springframework.stereotype.Component;
53 import org.springframework.web.client.HttpClientErrorException;
54 import org.springframework.web.client.HttpServerErrorException;
55 import org.springframework.web.client.RestTemplate;
56
57 @Component("PolicyAgentApi")
58 public class PolicyAgentApiImpl implements PolicyAgentApi {
59     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
60
61     RestTemplate restTemplate;
62
63     private static com.google.gson.Gson gson = new GsonBuilder() //
64         .serializeNulls() //
65         .create(); //
66
67     private final String urlPrefix;
68
69     @Autowired
70     public PolicyAgentApiImpl(
71         @org.springframework.beans.factory.annotation.Value("${policycontroller.url.prefix}") final String urlPrefix) {
72         this(urlPrefix, new RestTemplate());
73         logger.debug("ctor prefix '{}'", urlPrefix);
74     }
75
76     public PolicyAgentApiImpl(String urlPrefix, RestTemplate restTemplate) {
77         this.urlPrefix = urlPrefix;
78         this.restTemplate = restTemplate;
79     }
80
81     private String baseUrl() {
82         return urlPrefix;
83     }
84
85     @Value.Immutable
86     @Gson.TypeAdapters
87     interface PolicyTypeInfo {
88
89         public String name();
90
91         public String schema();
92     }
93
94     @Override
95     public ResponseEntity<String> getAllPolicyTypes() {
96         try {
97             String url = baseUrl() + "/policy_schemas";
98             ResponseEntity<String> rsp = this.restTemplate.getForEntity(url, String.class);
99             if (!rsp.getStatusCode().is2xxSuccessful()) {
100                 return rsp;
101             }
102
103             PolicyTypes result = new PolicyTypes();
104
105             JsonArray schemas = JsonParser.parseString(rsp.getBody()).getAsJsonArray();
106             for (JsonElement schema : schemas) {
107                 JsonObject schemaObj = schema.getAsJsonObject();
108                 if (schemaObj.get("title") != null) {
109                     String title = schemaObj.get("title").getAsString();
110                     String schemaAsStr = schemaObj.toString();
111                     PolicyType pt = new PolicyType(title, schemaAsStr);
112                     result.add(pt);
113                 } else {
114                     logger.warn("Ignoring schema: {}", schemaObj);
115                 }
116             }
117             return new ResponseEntity<>(gson.toJson(result), rsp.getStatusCode());
118         } catch (Exception e) {
119             return handleException(e);
120         }
121     }
122
123     @Override
124     public ResponseEntity<String> getPolicyInstancesForType(String type) {
125         String url = baseUrl() + "/policies?type={type}";
126         Map<String, ?> uriVariables = Map.of("type", type);
127         ResponseEntity<String> rsp = this.restTemplate.getForEntity(url, String.class, uriVariables);
128         if (!rsp.getStatusCode().is2xxSuccessful()) {
129             return rsp;
130         }
131
132         try {
133             Type listType = new TypeToken<List<ImmutablePolicyInfo>>() {}.getType();
134             List<PolicyInfo> rspParsed = gson.fromJson(rsp.getBody(), listType);
135             PolicyInstances result = new PolicyInstances();
136             for (PolicyInfo p : rspParsed) {
137                 result.add(p);
138             }
139             return new ResponseEntity<>(gson.toJson(result), rsp.getStatusCode());
140         } catch (Exception e) {
141             return handleException(e);
142         }
143     }
144
145     @Override
146     public ResponseEntity<Object> getPolicyInstance(String id) {
147         String url = baseUrl() + "/policy?id={id}";
148         Map<String, ?> uriVariables = Map.of("id", id);
149
150         return this.restTemplate.getForEntity(url, Object.class, uriVariables);
151     }
152
153     @Override
154     public ResponseEntity<String> putPolicy(String policyTypeIdString, String policyInstanceId, Object json,
155         String ric) {
156         String url = baseUrl() + "/policy?type={type}&id={id}&ric={ric}&service={service}";
157         Map<String, ?> uriVariables = Map.of( //
158             "type", policyTypeIdString, //
159             "id", policyInstanceId, //
160             "ric", ric, //
161             "service", "controlpanel");
162
163         try {
164             this.restTemplate.put(url, createJsonHttpEntity(json), uriVariables);
165             return new ResponseEntity<>(HttpStatus.OK);
166         } catch (Exception e) {
167             return handleException(e);
168         }
169     }
170
171     @Override
172     public ResponseEntity<String> deletePolicy(String policyInstanceId) {
173         String url = baseUrl() + "/policy?id={id}";
174         Map<String, ?> uriVariables = Map.of("id", policyInstanceId);
175         try {
176             this.restTemplate.delete(url, uriVariables);
177             return new ResponseEntity<>(HttpStatus.OK);
178         } catch (Exception e) {
179             return handleException(e);
180         }
181
182     }
183
184     @Value.Immutable
185     @Gson.TypeAdapters
186     interface RicInfo {
187         public String ricName();
188
189         public Collection<String> nodeNames();
190
191         public Collection<String> policyTypes();
192     }
193
194     @Override
195     public ResponseEntity<String> getRicsSupportingType(String typeName) {
196         String url = baseUrl() + "/rics?policyType={typeName}";
197         Map<String, ?> uriVariables = Map.of("typeName", typeName);
198         String rsp = this.restTemplate.getForObject(url, String.class, uriVariables);
199
200         try {
201             Type listType = new TypeToken<List<ImmutableRicInfo>>() {}.getType();
202             List<RicInfo> rspParsed = gson.fromJson(rsp, listType);
203             Collection<String> result = new ArrayList<>(rspParsed.size());
204             for (RicInfo ric : rspParsed) {
205                 result.add(ric.ricName());
206             }
207             return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
208         } catch (Exception e) {
209             return handleException(e);
210         }
211     }
212
213     private HttpEntity<Object> createJsonHttpEntity(Object content) {
214         HttpHeaders headers = new HttpHeaders();
215         headers.setContentType(MediaType.APPLICATION_JSON);
216         return new HttpEntity<>(content, headers);
217     }
218
219     private ResponseEntity<String> handleException(Exception throwable) {
220         if (throwable instanceof HttpClientErrorException) {
221             HttpClientErrorException e = (HttpClientErrorException) throwable;
222             return new ResponseEntity<>(e.getMessage(), e.getStatusCode());
223         } else if (throwable instanceof HttpServerErrorException) {
224             HttpServerErrorException e = (HttpServerErrorException) throwable;
225             return new ResponseEntity<>(e.getResponseBodyAsString(), e.getStatusCode());
226         }
227         return new ResponseEntity<>(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
228     }
229
230 }