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