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