Added support for https
[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         try {
79             final String url = "/policy_schemas";
80             ResponseEntity<String> rsp = webClient.getForEntity(url).block();
81             if (!rsp.getStatusCode().is2xxSuccessful()) {
82                 return rsp;
83             }
84
85             PolicyTypes result = new PolicyTypes();
86
87             JsonArray schemas = JsonParser.parseString(rsp.getBody()).getAsJsonArray();
88             for (JsonElement schema : schemas) {
89                 JsonObject schemaObj = schema.getAsJsonObject();
90                 if (schemaObj.get("title") != null) {
91                     String title = schemaObj.get("title").getAsString();
92                     String schemaAsStr = schemaObj.toString();
93                     PolicyType pt = new PolicyType(title, schemaAsStr);
94                     result.add(pt);
95                 } else {
96                     logger.warn("Ignoring schema: {}", schemaObj);
97                 }
98             }
99             return new ResponseEntity<>(gson.toJson(result), rsp.getStatusCode());
100         } catch (Exception e) {
101             return handleException(e);
102         }
103     }
104
105     @Override
106     public ResponseEntity<String> getPolicyInstancesForType(String type) {
107         try {
108             String url = "/policies?type=" + type;
109             ResponseEntity<String> rsp = webClient.getForEntity(url).block();
110             if (!rsp.getStatusCode().is2xxSuccessful()) {
111                 return rsp;
112             }
113
114             Type listType = new TypeToken<List<ImmutablePolicyInfo>>() {}.getType();
115             List<PolicyInfo> rspParsed = gson.fromJson(rsp.getBody(), listType);
116             PolicyInstances result = new PolicyInstances();
117             for (PolicyInfo p : rspParsed) {
118                 result.add(p);
119             }
120             return new ResponseEntity<>(gson.toJson(result), rsp.getStatusCode());
121         } catch (Exception e) {
122             return handleException(e);
123         }
124     }
125
126     @Override
127     public ResponseEntity<Object> getPolicyInstance(String id) {
128         try {
129             String url = "/policy?id=" + id;
130             ResponseEntity<String> rsp = webClient.getForEntity(url).block();
131             JsonObject obj = JsonParser.parseString(rsp.getBody()).getAsJsonObject();
132             String str = obj.toString();
133             return new ResponseEntity<>(str, rsp.getStatusCode());
134         } catch (Exception e) {
135             ResponseEntity<String> rsp = handleException(e);
136             return new ResponseEntity<>(rsp.getBody(), rsp.getStatusCode());
137         }
138     }
139
140     @Override
141     public ResponseEntity<String> putPolicy(String policyTypeIdString, String policyInstanceId, Object json,
142         String ric) {
143         String url =
144             "/policy?type=" + policyTypeIdString + "&id=" + policyInstanceId + "&ric=" + ric + "&service=controlpanel";
145
146         try {
147             String jsonStr = json.toString();
148             webClient.putForEntity(url, jsonStr).block();
149             return new ResponseEntity<>(HttpStatus.OK);
150         } catch (Exception e) {
151             return handleException(e);
152         }
153     }
154
155     @Override
156     public ResponseEntity<String> deletePolicy(String policyInstanceId) {
157         String url = "/policy?id=" + policyInstanceId;
158         try {
159             webClient.deleteForEntity(url).block();
160             return new ResponseEntity<>(HttpStatus.OK);
161         } catch (Exception e) {
162             return handleException(e);
163         }
164     }
165
166     @Value.Immutable
167     @Gson.TypeAdapters
168     interface RicInfo {
169         public String ricName();
170
171         public Collection<String> nodeNames();
172
173         public Collection<String> policyTypes();
174     }
175
176     @Override
177     public ResponseEntity<String> getRicsSupportingType(String typeName) {
178         try {
179             String url = "/rics?policyType=" + typeName;
180             ResponseEntity<String> rsp = webClient.getForEntity(url).block();
181
182             Type listType = new TypeToken<List<ImmutableRicInfo>>() {}.getType();
183             List<RicInfo> rspParsed = gson.fromJson(rsp.getBody(), listType);
184             Collection<String> result = new ArrayList<>(rspParsed.size());
185             for (RicInfo ric : rspParsed) {
186                 result.add(ric.ricName());
187             }
188             String json = gson.toJson(result);
189             return new ResponseEntity<>(json, HttpStatus.OK);
190         } catch (Exception e) {
191             return handleException(e);
192         }
193     }
194
195     private ResponseEntity<String> handleException(Exception throwable) {
196         if (throwable instanceof HttpClientErrorException) {
197             HttpClientErrorException e = (HttpClientErrorException) throwable;
198             return new ResponseEntity<>(e.getMessage(), e.getStatusCode());
199         } else if (throwable instanceof HttpServerErrorException) {
200             HttpServerErrorException e = (HttpServerErrorException) throwable;
201             return new ResponseEntity<>(e.getResponseBodyAsString(), e.getStatusCode());
202         } else if (throwable instanceof SSLException) {
203             SSLException e = (SSLException) throwable;
204             return new ResponseEntity<>("Could not create WebClient " + e.getMessage(),
205                 HttpStatus.INTERNAL_SERVER_ERROR);
206         }
207         return new ResponseEntity<>(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
208     }
209 }