Export SvcLogicFactory as service
[ccsdk/apps.git] / ms / sliboot / src / main / java / org / onap / ccsdk / apps / ms / sliboot / controllers / RestconfApiController.java
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.apps.ms.sliboot.controllers;
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.apps.ms.sliboot.swagger.ConfigApi;
28 import org.onap.ccsdk.apps.ms.sliboot.swagger.OperationalApi;
29 import org.onap.ccsdk.apps.ms.sliboot.swagger.OperationsApi;
30 import org.onap.ccsdk.apps.ms.sliboot.data.TestResultsOperationalRepository;
31 import org.onap.ccsdk.apps.ms.sliboot.swagger.model.*;
32 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
33 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
34 import org.onap.ccsdk.sli.core.sli.provider.base.SvcLogicServiceBase;
35 import org.onap.ccsdk.apps.ms.sliboot.data.TestResultConfig;
36 import org.onap.ccsdk.apps.ms.sliboot.data.TestResultsConfigRepository;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.boot.autoconfigure.domain.EntityScan;
41 import org.springframework.context.annotation.ComponentScan;
42 import org.springframework.http.HttpStatus;
43 import org.springframework.http.ResponseEntity;
44 import org.springframework.stereotype.Controller;
45
46 import javax.servlet.http.HttpServletRequest;
47 import javax.validation.Valid;
48 import java.util.*;
49
50 @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2020-02-20T12:50:11.207-05:00")
51
52 @Controller
53 @ComponentScan(basePackages = {"org.onap.ccsdk.apps.ms.sliboot.*", "org.onap.ccsdk.apps.services"})
54 @EntityScan("org.onap.ccsdk.apps.ms.sliboot.*")
55 public class RestconfApiController implements ConfigApi, OperationalApi, OperationsApi {
56
57         private final ObjectMapper objectMapper;
58         private final HttpServletRequest request;
59
60     @Autowired
61     protected SvcLogicServiceBase svc;
62
63     @Autowired
64         private TestResultsConfigRepository testResultsConfigRepository;
65
66     @Autowired
67         private TestResultsOperationalRepository testResultsOperationalRepository;
68
69         private static final Logger log = LoggerFactory.getLogger(RestconfApiController.class);
70
71         @org.springframework.beans.factory.annotation.Autowired
72         public RestconfApiController(ObjectMapper objectMapper, HttpServletRequest request) {
73                 this.objectMapper = objectMapper;
74                 this.request = request;
75         }
76
77
78         @Override
79         public Optional<ObjectMapper> getObjectMapper() {
80                 return Optional.ofNullable(objectMapper);
81         }
82
83         @Override
84         public Optional<HttpServletRequest> getRequest() {
85                 return Optional.ofNullable(request);
86         }
87         @Override
88         public Optional<String> getAcceptHeader() {
89                 return ConfigApi.super.getAcceptHeader();
90         }
91
92         @Override
93         public ResponseEntity<SliApiHealthcheck> operationsSLIAPIhealthcheckPost() {
94
95                 SliApiResponseFields respFields = new SliApiResponseFields();
96                 HttpStatus httpStatus = HttpStatus.OK;
97
98                 try {
99                         log.info("Calling SLI-API:healthcheck DG");
100                         SvcLogicContext ctxIn = new SvcLogicContext();
101                         SvcLogicContext ctxOut = svc.execute("sli", "healthcheck", null, "sync", ctxIn);
102                         Properties respProps = ctxOut.toProperties();
103
104                         respFields.setAckFinalIndicator(respProps.getProperty("ack-final-indicator", "Y"));
105                         respFields.setResponseCode(respProps.getProperty("error-code", "200"));
106                         respFields.setResponseMessage(respProps.getProperty("error-message", "Success"));
107                         respFields.setContextMemoryJson(propsToJson(respProps, "context-memory"));
108
109                 } catch (Exception e) {
110                         respFields.setAckFinalIndicator("true");
111                         respFields.setResponseCode("500");
112                         respFields.setResponseMessage(e.getMessage());
113                         httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
114                         log.error("Error calling healthcheck directed graph", e);
115
116                 }
117
118                 SliApiHealthcheck resp = new SliApiHealthcheck();
119                 resp.setOutput(respFields);
120                 return (new ResponseEntity<>(resp, httpStatus));
121         }
122
123         @Override
124         public ResponseEntity<SliApiVlbcheck> operationsSLIAPIvlbcheckPost() {
125
126                 SliApiResponseFields respFields = new SliApiResponseFields();
127                 HttpStatus httpStatus = HttpStatus.OK;
128
129                 try {
130                         log.info("Calling SLI-API:vlbcheck DG");
131                         SvcLogicContext ctxIn = new SvcLogicContext();
132                         SvcLogicContext ctxOut = svc.execute("sli", "vlbcheck", null, "sync", ctxIn);
133                         Properties respProps = ctxOut.toProperties();
134                         respFields.setAckFinalIndicator(respProps.getProperty("ack-final-indicator", "Y"));
135                         respFields.setResponseCode(respProps.getProperty("error-code", "200"));
136                         respFields.setResponseMessage(respProps.getProperty("error-message", "Success"));
137                         respFields.setContextMemoryJson(propsToJson(respProps, "context-memory"));
138
139                 } catch (Exception e) {
140                         respFields.setAckFinalIndicator("true");
141                         respFields.setResponseCode("500");
142                         respFields.setResponseMessage(e.getMessage());
143                         httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
144                         log.error("Error calling vlbcheck directed graph", e);
145
146                 }
147
148                 SliApiVlbcheck resp = new SliApiVlbcheck();
149                 resp.setOutput(respFields);
150                 return (new ResponseEntity<>(resp, httpStatus));
151         }
152
153         @Override
154         public ResponseEntity<SliApiExecuteGraph> operationsSLIAPIexecuteGraphPost(@Valid SliApiExecutegraphInputBodyparam executeGraphInput) {
155
156                 SvcLogicContext ctxIn = new SvcLogicContext();
157                 SliApiExecuteGraph resp = new SliApiExecuteGraph();
158                 SliApiResponseFields respFields = new SliApiResponseFields();
159                 String executeGraphInputJson = null;
160
161                 try {
162                          executeGraphInputJson = objectMapper.writeValueAsString(executeGraphInput);
163                          log.info("Input as JSON is "+executeGraphInputJson);
164                 } catch (JsonProcessingException e) {
165
166                         respFields.setAckFinalIndicator("true");
167                         respFields.setResponseCode("500");
168                         respFields.setResponseMessage(e.getMessage());
169                         log.error("Cannot create JSON from input object", e);
170                         resp.setOutput(respFields);
171                         return (new ResponseEntity<>(resp, HttpStatus.INTERNAL_SERVER_ERROR));
172
173                 }
174                 JsonObject jsonInput = new Gson().fromJson(executeGraphInputJson, JsonObject.class);
175                 JsonObject passthroughObj = jsonInput.get("input").getAsJsonObject();
176
177                 ctxIn.mergeJson("input", passthroughObj.toString());
178
179                 try {
180                         // Any of these can throw a nullpointer exception
181                         String calledModule = executeGraphInput.getInput().getModuleName();
182                         String calledRpc = executeGraphInput.getInput().getRpcName();
183                         String modeStr = executeGraphInput.getInput().getMode().toString();
184                         // execute should only throw a SvcLogicException
185                         SvcLogicContext ctxOut = svc.execute(calledModule, calledRpc, null, modeStr, ctxIn);
186                         Properties respProps = ctxOut.toProperties();
187
188                         respFields.setAckFinalIndicator(respProps.getProperty("ack-final-indicator", "Y"));
189                         respFields.setResponseCode(respProps.getProperty("error-code", "200"));
190                         respFields.setResponseMessage(respProps.getProperty("error-message", "SUCCESS"));
191                         respFields.setContextMemoryJson(propsToJson(respProps, "context-memory"));
192                         resp.setOutput(respFields);
193                         return (new ResponseEntity<>(resp, HttpStatus.valueOf(Integer.parseInt(respFields.getResponseCode()))));
194
195                 } catch (NullPointerException npe) {
196                         respFields.setAckFinalIndicator("true");
197                         respFields.setResponseCode("500");
198                         respFields.setResponseMessage("Check that you populated module, rpc and or mode correctly.");
199
200                         resp.setOutput(respFields);
201                         return (new ResponseEntity<>(resp, HttpStatus.INTERNAL_SERVER_ERROR));
202                 } catch (SvcLogicException e) {
203                         respFields.setAckFinalIndicator("true");
204                         respFields.setResponseCode("500");
205                         respFields.setResponseMessage(e.getMessage());
206                         resp.setOutput(respFields);
207                         return (new ResponseEntity<>(resp, HttpStatus.INTERNAL_SERVER_ERROR));
208                 }
209         }
210
211         @Override
212         public ResponseEntity<Void> configSLIAPItestResultsSLIAPItestResultTestIdentifierDelete(String testIdentifier) {
213
214                 List<TestResultConfig> testResultConfigs = testResultsConfigRepository.findByTestIdentifier(testIdentifier);
215
216                 if (testResultConfigs != null) {
217                         Iterator<TestResultConfig> testResultConfigIterator = testResultConfigs.iterator();
218                         while (testResultConfigIterator.hasNext()) {
219                                 testResultsConfigRepository.delete(testResultConfigIterator.next());
220                         }
221                 }
222
223                 return (new ResponseEntity<>(HttpStatus.OK));
224         }
225
226         @Override
227         public ResponseEntity<Void> configSLIAPItestResultsDelete() {
228
229                 testResultsConfigRepository.deleteAll();
230
231                 return (new ResponseEntity<>(HttpStatus.OK));
232         }
233
234         @Override
235         public ResponseEntity<SliApiTestResults> operationalSLIAPItestResultsGet() {
236
237                 SliApiTestResults results = new SliApiTestResults();
238
239                 testResultsOperationalRepository.findAll().forEach(testResult -> {
240                         SliApiTestresultsTestResult item = null;
241                         try {
242                                 item = objectMapper.readValue(testResult.getResults(), SliApiTestresultsTestResult.class);
243                                 results.addTestResultItem(item);
244                         } catch (JsonProcessingException e) {
245                                 log.error("Could not convert testResult", e);
246                         }
247                 });
248
249
250                 return new ResponseEntity<>(results, HttpStatus.OK);
251         }
252
253         @Override
254         public ResponseEntity<SliApiTestresultsTestResult> configSLIAPItestResultsSLIAPItestResultTestIdentifierGet(String testIdentifier) {
255
256                 List<TestResultConfig> testResultConfigs = testResultsConfigRepository.findByTestIdentifier(testIdentifier);
257
258                 if ((testResultConfigs == null) || (testResultConfigs.size() == 0)) {
259                         return new ResponseEntity<>(HttpStatus.NOT_FOUND);
260                 } else {
261                         TestResultConfig testResultConfig = testResultConfigs.get(0);
262                         SliApiTestresultsTestResult testResult = null;
263                         try {
264                                 testResult = objectMapper.readValue(testResultConfig.getResults(), SliApiTestresultsTestResult.class);
265                         } catch (JsonProcessingException e) {
266                                 log.error("Cannot convert test result", e);
267                                 return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
268                         }
269
270
271                         return new ResponseEntity<>(testResult, HttpStatus.OK);
272                 }
273         }
274
275         @Override
276         public ResponseEntity<SliApiTestResults> configSLIAPItestResultsGet() {
277
278                 if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) {
279                 } else {
280                         log.warn("ObjectMapper or HttpServletRequest not configured in default RestconfApi interface so no example is generated");
281                 }
282
283                 SliApiTestResults results = new SliApiTestResults();
284
285                 testResultsConfigRepository.findAll().forEach(testResult -> {
286                         SliApiTestresultsTestResult item = null;
287                         try {
288                                 item = objectMapper.readValue(testResult.getResults(), SliApiTestresultsTestResult.class);
289                                 results.addTestResultItem(item);
290                         } catch (JsonProcessingException e) {
291                                 log.error("Could not convert testResult", e);
292                         }
293                 });
294
295
296                 return new ResponseEntity<>(results, HttpStatus.OK);
297         }
298
299         @Override
300         public ResponseEntity<Void> configSLIAPItestResultsSLIAPItestResultTestIdentifierPut(String testIdentifier, @Valid SliApiTestresultsTestResult testResult) {
301
302                 if(getObjectMapper().isPresent() && getAcceptHeader().isPresent()) {
303                 } else {
304                         log.warn("ObjectMapper or HttpServletRequest not configured in default RestconfApi interface so no example is generated");
305                 }
306
307                 List<TestResultConfig> testResultConfigs = testResultsConfigRepository.findByTestIdentifier(testIdentifier);
308                 Iterator<TestResultConfig> testResultIter = testResultConfigs.iterator();
309                 while (testResultIter.hasNext()) {
310                         testResultsConfigRepository.delete(testResultIter.next());
311                 }
312
313                 TestResultConfig testResultConfig = null;
314                 try {
315                         testResultConfig = new TestResultConfig(testResult.getTestIdentifier(), objectMapper.writeValueAsString(testResult));
316                         testResultsConfigRepository.save(testResultConfig);
317                 } catch (JsonProcessingException e) {
318                         log.error("Could not save test result", e);
319                         return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
320                 }
321
322                 return new ResponseEntity<>(HttpStatus.OK);
323         }
324
325         @Override
326         public ResponseEntity<Void> configSLIAPItestResultsPost(@Valid SliApiTestResults testResults) {
327
328                 List<SliApiTestresultsTestResult> resultList = testResults.getTestResult();
329
330                 if (resultList == null) {
331                         log.error("Invalid input - no test results list");
332                         return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
333                 }
334                 Iterator<SliApiTestresultsTestResult> resultIterator = resultList.iterator();
335
336                 while (resultIterator.hasNext()) {
337                         SliApiTestresultsTestResult curResult = resultIterator.next();
338                         try {
339                                 testResultsConfigRepository.save(new TestResultConfig(curResult.getTestIdentifier(), objectMapper.writeValueAsString(curResult)));
340                         } catch (JsonProcessingException e) {
341                                 log.error("Could not save test result", e);
342                                 return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
343                         }
344                 }
345
346                 return new ResponseEntity<>(HttpStatus.OK);
347         }
348
349         @Override
350         public ResponseEntity<Void> configSLIAPItestResultsPut(@Valid SliApiTestResults testResults) {
351
352                 testResultsConfigRepository.deleteAll();
353
354                 List<SliApiTestresultsTestResult> resultList = testResults.getTestResult();
355
356                 Iterator<SliApiTestresultsTestResult> resultIterator = resultList.iterator();
357
358
359                 while (resultIterator.hasNext()) {
360                         SliApiTestresultsTestResult curResult = resultIterator.next();
361                         try {
362                                 testResultsConfigRepository.save(new TestResultConfig(curResult.getTestIdentifier(), objectMapper.writeValueAsString(curResult)));
363                         } catch (JsonProcessingException e) {
364                                 log.error("Could not save test result", e);
365                                 return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
366                         }
367                 }
368
369                 return new ResponseEntity<>(HttpStatus.OK);
370         }
371
372         public static String propsToJson(Properties props, String root)
373         {
374                 StringBuffer sbuff = new StringBuffer();
375
376                 sbuff.append("{ \""+root+"\" : { ");
377                 boolean needComma = false;
378                 for (Map.Entry<Object, Object> prop : props.entrySet()) {
379                         sbuff.append("\""+(String) prop.getKey()+"\" : \""+(String)prop.getValue()+"\"");
380                         if (needComma) {
381                                 sbuff.append(" , ");
382                         } else {
383                                 needComma = true;
384                         }
385                 }
386                 sbuff.append(" } }");
387
388                 return(sbuff.toString());
389         }
390
391 }