Improved error printouts
[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                 String title = schemaObj.get("title").getAsString();
109                 String schemaAsStr = schemaObj.toString();
110                 PolicyType pt = new PolicyType(title, schemaAsStr);
111                 result.add(pt);
112             }
113             return new ResponseEntity<>(gson.toJson(result), rsp.getStatusCode());
114         } catch (Exception e) {
115             return handleException(e);
116         }
117     }
118
119     @Override
120     public ResponseEntity<String> getPolicyInstancesForType(String type) {
121         String url = baseUrl() + "/policies?type={type}";
122         Map<String, ?> uriVariables = Map.of("type", type);
123         ResponseEntity<String> rsp = this.restTemplate.getForEntity(url, String.class, uriVariables);
124         if (!rsp.getStatusCode().is2xxSuccessful()) {
125             return rsp;
126         }
127
128         try {
129             Type listType = new TypeToken<List<ImmutablePolicyInfo>>() {}.getType();
130             List<PolicyInfo> rspParsed = gson.fromJson(rsp.getBody(), listType);
131             PolicyInstances result = new PolicyInstances();
132             for (PolicyInfo p : rspParsed) {
133                 result.add(p);
134             }
135             return new ResponseEntity<>(gson.toJson(result), rsp.getStatusCode());
136         } catch (Exception e) {
137             return handleException(e);
138         }
139     }
140
141     @Override
142     public ResponseEntity<Object> getPolicyInstance(String id) {
143         String url = baseUrl() + "/policy?id={id}";
144         Map<String, ?> uriVariables = Map.of("id", id);
145
146         return this.restTemplate.getForEntity(url, Object.class, uriVariables);
147     }
148
149     @Override
150     public ResponseEntity<String> putPolicy(String policyTypeIdString, String policyInstanceId, Object json,
151         String ric) {
152         String url = baseUrl() + "/policy?type={type}&id={id}&ric={ric}&service={service}";
153         Map<String, ?> uriVariables = Map.of( //
154             "type", policyTypeIdString, //
155             "id", policyInstanceId, //
156             "ric", ric, //
157             "service", "controlpanel");
158
159         try {
160             this.restTemplate.put(url, createJsonHttpEntity(json), uriVariables);
161             return new ResponseEntity<>(HttpStatus.OK);
162         } catch (Exception e) {
163             return handleException(e);
164         }
165     }
166
167     @Override
168     public ResponseEntity<String> deletePolicy(String policyInstanceId) {
169         String url = baseUrl() + "/policy?id={id}";
170         Map<String, ?> uriVariables = Map.of("id", policyInstanceId);
171         try {
172             this.restTemplate.delete(url, uriVariables);
173             return new ResponseEntity<>(HttpStatus.OK);
174         } catch (Exception e) {
175             return handleException(e);
176         }
177
178     }
179
180     @Value.Immutable
181     @Gson.TypeAdapters
182     interface RicInfo {
183         public String ricName();
184
185         public Collection<String> nodeNames();
186
187         public Collection<String> policyTypes();
188     }
189
190     @Override
191     public ResponseEntity<String> getRicsSupportingType(String typeName) {
192         String url = baseUrl() + "/rics?policyType={typeName}";
193         Map<String, ?> uriVariables = Map.of("typeName", typeName);
194         String rsp = this.restTemplate.getForObject(url, String.class, uriVariables);
195
196         try {
197             Type listType = new TypeToken<List<ImmutableRicInfo>>() {}.getType();
198             List<RicInfo> rspParsed = gson.fromJson(rsp, listType);
199             Collection<String> result = new ArrayList<>(rspParsed.size());
200             for (RicInfo ric : rspParsed) {
201                 result.add(ric.ricName());
202             }
203             return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
204         } catch (Exception e) {
205             return handleException(e);
206         }
207     }
208
209     private HttpEntity<Object> createJsonHttpEntity(Object content) {
210         HttpHeaders headers = new HttpHeaders();
211         headers.setContentType(MediaType.APPLICATION_JSON);
212         return new HttpEntity<>(content, headers);
213     }
214
215     private ResponseEntity<String> handleException(Exception throwable) {
216         if (throwable instanceof HttpClientErrorException) {
217             HttpClientErrorException e = (HttpClientErrorException) throwable;
218             return new ResponseEntity<>(e.getMessage(), e.getStatusCode());
219         } else if (throwable instanceof HttpServerErrorException) {
220             HttpServerErrorException e = (HttpServerErrorException) throwable;
221             return new ResponseEntity<>(e.getResponseBodyAsString(), e.getStatusCode());
222         }
223         return new ResponseEntity<>(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
224     }
225
226 }