aa9a9d7e83be0769c846321425f8572d125f1fc1
[ccsdk/sli.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - CCSDK
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.ccsdk.sli.core.sliapi.springboot.controllers.swagger;
22
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import com.google.gson.Gson;
26 import com.google.gson.JsonObject;
27 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
28 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
29 import org.onap.ccsdk.sli.core.sli.provider.base.SvcLogicServiceBase;
30 import org.onap.ccsdk.sli.core.sliapi.model.ExecuteGraphInput;
31 import org.onap.ccsdk.sli.core.sliapi.model.ResponseFields;
32 import org.onap.ccsdk.sli.core.sliapi.model.TestResult;
33 import org.onap.ccsdk.sli.core.sliapi.model.TestResults;
34 import org.onap.ccsdk.sli.core.sliapi.springboot.controllers.data.TestResultConfig;
35 import org.onap.ccsdk.sli.core.sliapi.springboot.controllers.data.TestResultsConfigRepository;
36 import org.onap.ccsdk.sli.core.sliapi.springboot.controllers.data.TestResultsOperationalRepository;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
41 import org.springframework.boot.autoconfigure.domain.EntityScan;
42 import org.springframework.context.annotation.ComponentScan;
43 import org.springframework.http.HttpStatus;
44 import org.springframework.http.ResponseEntity;
45 import org.springframework.stereotype.Controller;
46
47 import javax.servlet.http.HttpServletRequest;
48 import javax.validation.Valid;
49 import java.util.*;
50
51 @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2020-02-20T12:50:11.207-05:00")
52
53 @Controller
54 @ComponentScan(basePackages = {"org.onap.ccsdk.sli.core.sliapi.springboot.*"})
55 @EntityScan("org.onap.ccsdk.sli.core.sliapi.springboot.*")
56 public class RestconfApiController implements RestconfApi {
57
58         private final ObjectMapper objectMapper;
59         private final HttpServletRequest request;
60
61     @Autowired
62     protected SvcLogicServiceBase svc;
63
64     @Autowired
65         private TestResultsConfigRepository testResultsConfigRepository;
66
67     @Autowired
68         private TestResultsOperationalRepository testResultsOperationalRepository;
69
70         private static final Logger log = LoggerFactory.getLogger(RestconfApiController.class);
71
72         @org.springframework.beans.factory.annotation.Autowired
73         public RestconfApiController(ObjectMapper objectMapper, HttpServletRequest request) {
74                 this.objectMapper = objectMapper;
75                 this.request = request;
76         }
77
78         @Override
79         public ResponseEntity<ResponseFields> healthcheck() {
80                 ResponseFields resp = new ResponseFields();
81
82                 try {
83                         log.info("Calling SLI-API:healthcheck DG");
84                         SvcLogicContext ctxIn = new SvcLogicContext();
85                         SvcLogicContext ctxOut = svc.execute("sli", "healthcheck", null, "sync", ctxIn);
86                         Properties respProps = ctxOut.toProperties();
87
88                         resp.setAckFinalIndicator(respProps.getProperty("ack-final-indicator", "Y"));
89                         resp.setResponseCode(respProps.getProperty("error-code", "200"));
90                         resp.setResponseMessage(respProps.getProperty("error-message", "Success"));
91                         resp.setContextMemoryJson(propsToJson(respProps, "context-memory"));
92
93                         return (new ResponseEntity<>(resp, HttpStatus.OK));
94                 } catch (Exception e) {
95                         resp.setAckFinalIndicator("true");
96                         resp.setResponseCode("500");
97                         resp.setResponseMessage(e.getMessage());
98                         log.error("Error calling healthcheck directed graph", e);
99
100                 }
101                 return (new ResponseEntity<>(resp, HttpStatus.INTERNAL_SERVER_ERROR));
102         }
103
104         @Override
105         public ResponseEntity<ResponseFields> vlbcheck() {
106                 ResponseFields resp = new ResponseFields();
107
108                 try {
109                         log.info("Calling SLI-API:vlbcheck DG");
110                         SvcLogicContext ctxIn = new SvcLogicContext();
111                         SvcLogicContext ctxOut = svc.execute("sli", "vlbcheck", null, "sync", ctxIn);
112                         Properties respProps = ctxOut.toProperties();
113                         resp.setAckFinalIndicator(respProps.getProperty("ack-final-indicator", "Y"));
114                         resp.setResponseCode(respProps.getProperty("error-code", "200"));
115                         resp.setResponseMessage(respProps.getProperty("error-message", "Success"));
116                         resp.setContextMemoryJson(propsToJson(respProps, "context-memory"));
117
118                         return (new ResponseEntity<>(resp, HttpStatus.OK));
119                 } catch (Exception e) {
120                         resp.setAckFinalIndicator("true");
121                         resp.setResponseCode("500");
122                         resp.setResponseMessage(e.getMessage());
123                         log.error("Error calling vlbcheck directed graph", e);
124
125                 }
126                 return (new ResponseEntity<>(resp, HttpStatus.INTERNAL_SERVER_ERROR));
127         }
128
129
130         @Override
131         public Optional<ObjectMapper> getObjectMapper() {
132                 return Optional.ofNullable(objectMapper);
133         }
134
135         @Override
136         public Optional<HttpServletRequest> getRequest() {
137                 return Optional.ofNullable(request);
138         }
139
140         @Override
141         public ResponseEntity<ResponseFields> executeGraph(@Valid ExecuteGraphInput executeGraphInput) {
142                 SvcLogicContext ctxIn = new SvcLogicContext();
143                 ResponseFields resp = new ResponseFields();
144                 String executeGraphInputJson = null;
145
146                 try {
147                          executeGraphInputJson = objectMapper.writeValueAsString(executeGraphInput);
148                          log.info("Input as JSON is "+executeGraphInputJson);
149                 } catch (JsonProcessingException e) {
150
151                         resp.setAckFinalIndicator("true");
152                         resp.setResponseCode("500");
153                         resp.setResponseMessage(e.getMessage());
154                         log.error("Cannot create JSON from input object", e);
155                         return (new ResponseEntity<>(resp, HttpStatus.INTERNAL_SERVER_ERROR));
156
157                 }
158                 JsonObject jsonInput = new Gson().fromJson(executeGraphInputJson, JsonObject.class);
159                 JsonObject passthroughObj = jsonInput.get("input").getAsJsonObject();
160
161                 ctxIn.mergeJson("input", passthroughObj.toString());
162
163                 try {
164                         // Any of these can throw a nullpointer exception
165                         String calledModule = executeGraphInput.getInput().getModuleName();
166                         String calledRpc = executeGraphInput.getInput().getRpcName();
167                         String modeStr = executeGraphInput.getInput().getMode();
168                         // execute should only throw a SvcLogicException
169                         SvcLogicContext ctxOut = svc.execute(calledModule, calledRpc, null, modeStr, ctxIn);
170                         Properties respProps = ctxOut.toProperties();
171
172                         resp.setAckFinalIndicator(respProps.getProperty("ack-final-indicator", "Y"));
173                         resp.setResponseCode(respProps.getProperty("error-code", "200"));
174                         resp.setResponseMessage(respProps.getProperty("error-message", "SUCCESS"));
175                         resp.setContextMemoryJson(propsToJson(respProps, "context-memory"));
176                         return (new ResponseEntity<>(resp, HttpStatus.valueOf(Integer.parseInt(resp.getResponseCode()))));
177
178                 } catch (NullPointerException npe) {
179                         resp.setAckFinalIndicator("true");
180                         resp.setResponseCode("500");
181                         resp.setResponseMessage("Check that you populated module, rpc and or mode correctly.");
182
183                         return (new ResponseEntity<>(resp, HttpStatus.INTERNAL_SERVER_ERROR));
184                 } catch (SvcLogicException e) {
185                         resp.setAckFinalIndicator("true");
186                         resp.setResponseCode("500");
187                         resp.setResponseMessage(e.getMessage());
188
189                         return (new ResponseEntity<>(resp, HttpStatus.INTERNAL_SERVER_ERROR));
190                 }
191         }
192
193         @Override
194         public ResponseEntity<Void> deleteTestResult(String testIdentifier) {
195
196                 List<TestResultConfig> testResultConfigs = testResultsConfigRepository.findByTestIdentifier(testIdentifier);
197
198                 if (testResultConfigs != null) {
199                         Iterator<TestResultConfig> testResultConfigIterator = testResultConfigs.iterator();
200                         while (testResultConfigIterator.hasNext()) {
201                                 testResultsConfigRepository.delete(testResultConfigIterator.next());
202                         }
203                 }
204
205                 return (new ResponseEntity<>(HttpStatus.OK));
206         }
207
208         @Override
209         public ResponseEntity<Void> deleteTestResults() {
210
211                 testResultsConfigRepository.deleteAll();
212
213                 return (new ResponseEntity<>(HttpStatus.OK));
214         }
215
216         @Override
217         public ResponseEntity<TestResults> gETTestResults() {
218
219                 TestResults results = new TestResults();
220
221                 testResultsOperationalRepository.findAll().forEach(testResult -> {
222                         TestResult item = null;
223                         try {
224                                 item = objectMapper.readValue(testResult.getResults(), TestResult.class);
225                                 results.addTestResultsItem(item);
226                         } catch (JsonProcessingException e) {
227                                 log.error("Could not convert testResult", e);
228                         }
229                 });
230
231
232                 return new ResponseEntity<>(results, HttpStatus.OK);
233         }
234
235         @Override
236         public ResponseEntity<TestResult> getTestResult(String testIdentifier) {
237                 List<TestResultConfig> testResultConfigs = testResultsConfigRepository.findByTestIdentifier(testIdentifier);
238
239                 if ((testResultConfigs == null) || (testResultConfigs.size() == 0)) {
240                         return new ResponseEntity<>(HttpStatus.NOT_FOUND);
241                 } else {
242                         TestResultConfig testResultConfig = testResultConfigs.get(0);
243                         TestResult testResult = null;
244                         try {
245                                 testResult = objectMapper.readValue(testResultConfig.getResults(), TestResult.class);
246                         } catch (JsonProcessingException e) {
247                                 log.error("Cannot convert test result", e);
248                                 return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
249                         }
250
251
252                         return new ResponseEntity<>(testResult, HttpStatus.OK);
253                 }
254         }
255
256         @Override
257         public ResponseEntity<TestResults> getTestResults() {
258                 if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) {
259                 } else {
260                         log.warn("ObjectMapper or HttpServletRequest not configured in default RestconfApi interface so no example is generated");
261                 }
262
263                 TestResults results = new TestResults();
264
265                 testResultsConfigRepository.findAll().forEach(testResult -> {
266                         TestResult item = null;
267                         try {
268                                 item = objectMapper.readValue(testResult.getResults(), TestResult.class);
269                                 results.addTestResultsItem(item);
270                         } catch (JsonProcessingException e) {
271                                 log.error("Could not convert testResult", e);
272                         }
273                 });
274
275
276                 return new ResponseEntity<>(results, HttpStatus.OK);
277         }
278
279         @Override
280         public ResponseEntity<TestResult> pUTTestResult(String testIdentifier, @Valid TestResult testResult) {
281                 if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) {
282                 } else {
283                         log.warn("ObjectMapper or HttpServletRequest not configured in default RestconfApi interface so no example is generated");
284                 }
285
286                 List<TestResultConfig> testResultConfigs = testResultsConfigRepository.findByTestIdentifier(testIdentifier);
287                 Iterator<TestResultConfig> testResultIter = testResultConfigs.iterator();
288                 while (testResultIter.hasNext()) {
289                         testResultsConfigRepository.delete(testResultIter.next());
290                 }
291
292                 TestResultConfig testResultConfig = null;
293                 try {
294                         testResultConfig = new TestResultConfig(testResult.getTestIdentifier(), objectMapper.writeValueAsString(testResult));
295                         testResultsConfigRepository.save(testResultConfig);
296                 } catch (JsonProcessingException e) {
297                         log.error("Could not save test result", e);
298                         return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
299                 }
300
301                 return new ResponseEntity<>(testResult, HttpStatus.OK);
302         }
303
304         @Override
305         public ResponseEntity<TestResults> postTestResults(@Valid TestResults testResults) {
306                 List<TestResult> resultList = testResults.getTestResults();
307
308                 Iterator<TestResult> resultIterator = resultList.iterator();
309
310                 while (resultIterator.hasNext()) {
311                         TestResult curResult = resultIterator.next();
312                         try {
313                                 testResultsConfigRepository.save(new TestResultConfig(curResult.getTestIdentifier(), objectMapper.writeValueAsString(curResult)));
314                         } catch (JsonProcessingException e) {
315                                 log.error("Could not save test result", e);
316                                 return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
317                         }
318                 }
319
320                 return new ResponseEntity<>(testResults, HttpStatus.OK);
321         }
322
323         @Override
324         public ResponseEntity<TestResults> putTestResults(@Valid TestResults testResults) {
325                 testResultsConfigRepository.deleteAll();
326
327                 List<TestResult> resultList = testResults.getTestResults();
328
329                 Iterator<TestResult> resultIterator = resultList.iterator();
330
331
332                 while (resultIterator.hasNext()) {
333                         TestResult curResult = resultIterator.next();
334                         try {
335                                 testResultsConfigRepository.save(new TestResultConfig(curResult.getTestIdentifier(), objectMapper.writeValueAsString(curResult)));
336                         } catch (JsonProcessingException e) {
337                                 log.error("Could not save test result", e);
338                                 return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
339                         }
340                 }
341
342                 return new ResponseEntity<>(testResults, HttpStatus.OK);
343         }
344
345         public static String propsToJson(Properties props, String root)
346         {
347                 StringBuffer sbuff = new StringBuffer();
348
349                 sbuff.append("{ \""+root+"\" : { ");
350                 boolean needComma = false;
351                 for (Map.Entry<Object, Object> prop : props.entrySet()) {
352                         sbuff.append("\""+(String) prop.getKey()+"\" : \""+(String)prop.getValue()+"\"");
353                         if (needComma) {
354                                 sbuff.append(" , ");
355                         } else {
356                                 needComma = true;
357                         }
358                 }
359                 sbuff.append(" } }");
360
361                 return(sbuff.toString());
362         }
363
364 }