Jenkins job testing
[nonrtric.git] / near-rt-ric-simulator / nearric-service / src / main / java / org / onap / nearric / simulator / service / A1PApiServiceImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.nearric.simulator.service;
22
23 import java.io.IOException;
24 import java.util.HashMap;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.Set;
28
29 import javax.servlet.http.HttpServletRequest;
30
31 import org.onap.nearric.simulator.model.PolicyInstance;
32 import org.onap.nearric.simulator.model.PolicyType;
33 import org.oransc.ric.a1med.api.model.InlineResponse200;
34 import org.oransc.ric.a1med.api.model.PolicyTypeSchema;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.http.HttpStatus;
38 import org.springframework.http.ResponseEntity;
39 import org.springframework.stereotype.Service;
40
41 import com.fasterxml.jackson.core.JsonParseException;
42 import com.fasterxml.jackson.core.JsonParser;
43 import com.fasterxml.jackson.databind.JsonNode;
44 import com.fasterxml.jackson.databind.ObjectMapper;
45 import com.github.fge.jackson.JsonLoader;
46 import com.github.fge.jsonschema.core.exceptions.ProcessingException;
47 import com.github.fge.jsonschema.core.report.ProcessingMessage;
48 import com.github.fge.jsonschema.core.report.ProcessingReport;
49 import com.github.fge.jsonschema.main.JsonSchema;
50 import com.github.fge.jsonschema.main.JsonSchemaFactory;
51
52 /**
53  * This class provides the service implementation of all the A1 operation
54  * 
55  * @author lathishbabu.ganesan@est.tech
56  *
57  */
58
59 @Service
60 public class A1PApiServiceImpl {
61
62         private static final Logger log = LoggerFactory.getLogger(A1PApiServiceImpl.class);
63
64         private HashMap<String, PolicyType> policyTypes = new HashMap<String, PolicyType>();
65
66         private ObjectMapper objectMapper = null;
67
68         private HttpServletRequest request = null;
69
70         public boolean validateSchema(String jsonData, String jsonSchema) {
71                 ProcessingReport report = null;
72                 boolean result = false;
73                 try {
74                         log.info("Applying schema: @<@<" + jsonSchema + ">@>@ to data: #<#<" + jsonData + ">#>#");
75                         JsonNode schemaNode = JsonLoader.fromString(jsonSchema);
76                         JsonNode data = JsonLoader.fromString(jsonData);
77                         JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
78                         JsonSchema schema = factory.getJsonSchema(schemaNode);
79                         report = schema.validate(data);
80                 } catch (JsonParseException jpex) {
81                         log.info("Error. Something went wrong trying to parse json data: #<#<" + jsonData
82                                         + ">#># or json schema: @<@<" + jsonSchema + ">@>@. Are the double quotes included? "
83                                         + jpex.getMessage());
84                 } catch (ProcessingException pex) {
85                         log.info("Error. Something went wrong trying to process json data: #<#<" + jsonData
86                                         + ">#># with json schema: @<@<" + jsonSchema + ">@>@ " + pex.getMessage());
87                 } catch (IOException e) {
88                         log.info("Error. Something went wrong trying to read json data: #<#<" + jsonData
89                                         + ">#># or json schema: @<@<" + jsonSchema + ">@>@");
90                 }
91                 if (report != null) {
92                         Iterator<ProcessingMessage> iter = report.iterator();
93                         while (iter.hasNext()) {
94                                 ProcessingMessage pm = iter.next();
95                                 log.info("Processing Message: " + pm.getMessage());
96                         }
97                         result = report.isSuccess();
98                 }
99                 log.info("Result=" + result);
100                 return result;
101         }
102
103         public A1PApiServiceImpl() {
104         }
105
106         public void set(ObjectMapper objectMapper, HttpServletRequest request) {
107                 this.objectMapper = objectMapper;
108                 this.request = request;
109         }
110         
111     public void reset() {
112         log.info("Resetting db");
113         policyTypes.clear();
114     }
115
116         public ResponseEntity<Void> createReplaceType(Integer policyTypeId, PolicyTypeSchema policyTypeSchema) {
117                 log.info("createReplaceType - policyTypeId: " + policyTypeId);
118                 log.info("createReplaceType - policyTypeSchema: " + policyTypeSchema);
119
120                 if (policyTypeId == null || policyTypeSchema == null || policyTypeSchema.getName() == null) {
121                         log.info("createReplaceType - bad parameters");
122                         return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
123                 }
124
125                 if (policyTypeSchema.getPolicyTypeId().intValue() != policyTypeId.intValue()) {
126                         log.info("createReplaceType - policytype id mismatch between request and policyTypeSchema");
127                         return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
128                 }
129
130                 if (policyTypes.containsKey(policyTypeId.toString())) {
131                         log.info("createReplaceType - policytype already exists");
132                         return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
133                 }
134
135                 PolicyType policyType = new PolicyType(policyTypeId, policyTypeSchema);
136                 policyTypes.put(policyTypeId.toString(), policyType);
137                 log.info("createReplaceType - created ok");
138
139                 return new ResponseEntity<Void>(HttpStatus.CREATED);
140         }
141
142         public ResponseEntity<Void> deleteType(Integer policyTypeId) {
143                 log.info("deleteType - policyTypeId: " + policyTypeId);
144
145                 if (policyTypeId == null) {
146                         log.info("deleteType - bad parameter");
147                         return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
148                 }
149
150                 PolicyType policyType = policyTypes.get(policyTypeId.toString());
151
152                 if (policyType == null) {
153                         log.info("deleteType - policytype does not exists");
154                         return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
155                 }
156
157                 if (policyType.getNumberInstances() > 0) {
158                         log.info("deleteType - cannot delete, instances exists");
159                         return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
160                 }
161                 policyTypes.remove(policyTypeId.toString());
162
163                 log.info("deleteType - deleted ok");
164                 return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
165         }
166
167         public ResponseEntity<Void> deleteInstance(Integer policyTypeId, String policyInstanceId) {
168
169                 log.info("deleteInstance - policyTypeId: " + policyTypeId);
170                 log.info("deleteInstance - policyInstanceId: " + policyInstanceId);
171
172                 if (policyTypeId == null || policyInstanceId == null) {
173                         log.info("deleteInstance - bad parameters");
174                         return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
175                 }
176
177                 PolicyType policyType = policyTypes.get(policyTypeId.toString());
178
179                 if (policyType == null) {
180                         log.info("deleteType - policytype does not exists");
181                         return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
182                 }
183                 PolicyInstance policyInstance = policyType.getInstance(policyInstanceId);
184                 if (policyInstance == null) {
185                         log.info("deleteType - instance does not exists");
186                         return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
187                 }
188                 policyType.delete(policyInstanceId);
189
190                 log.info("deleteInstance - deleted ok");
191                 return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
192
193         }
194
195         public ResponseEntity<PolicyTypeSchema> getPolicyTypeSchema(Integer policyTypeId) {
196                 log.info("getPolicyTypeSchema - policyTypeId: " + policyTypeId);
197
198                 if (policyTypeId == null) {
199                         log.info("getPolicyTypeSchema - bad parameter");
200                         return new ResponseEntity<PolicyTypeSchema>(HttpStatus.NOT_FOUND);
201                 }
202
203                 String accept = request.getHeader("Accept");
204                 if (accept != null && accept.contains("application/json")) {
205                         String res = null;
206                         try {
207                                 PolicyType policyType = policyTypes.get(policyTypeId.toString());
208
209                                 if (policyType == null) {
210                                         log.info("getPolicyTypeSchema - policytype does not exists");
211                                         return new ResponseEntity<PolicyTypeSchema>(HttpStatus.NOT_FOUND);
212                                 }
213
214                                 String json = null;
215                                 PolicyTypeSchema schema = policyType.getSchema();
216                                 String createSchema = "{}";
217                                 try {
218                                         // Convert Map to JSON
219                                         json = objectMapper.writeValueAsString(schema);
220                                         // Print JSON output
221                                         log.info("getPolicyTypeSchema - schema: " + json);
222
223                                         createSchema = objectMapper.writeValueAsString(schema.getCreateSchema());
224                                         log.info("getPolicyTypeSchema - createSchema: " + createSchema);
225                                 } catch (Exception e) {
226                                         e.printStackTrace();
227                                         log.info("getPolicyTypeSchema - schema corrupt");
228                                         return new ResponseEntity<PolicyTypeSchema>(HttpStatus.INTERNAL_SERVER_ERROR);
229                                 }
230                                 res = "{\n  \"name\" : \"" + schema.getName() + "\",\n  \"description\" : \"" + schema.getDescription()
231                                                 + "\",\n  \"create_schema\" : " + createSchema + ",\n  \"policy_type_id\" : "
232                                                 + schema.getPolicyTypeId().intValue() + "\n}";
233                                 log.info("getPolicyTypeSchema - json schema: " + res);
234                                 return new ResponseEntity<PolicyTypeSchema>(objectMapper.readValue(res, PolicyTypeSchema.class),
235                                                 HttpStatus.OK);
236                         } catch (Exception e) {
237                                 e.printStackTrace();
238                                 log.info("getPolicyTypeSchema - Couldn't serialize response for content type application/json");
239                                 return new ResponseEntity<PolicyTypeSchema>(HttpStatus.INTERNAL_SERVER_ERROR);
240                         }
241                 }
242                 log.info("getPolicyTypeSchema - not implemented");
243                 return new ResponseEntity<PolicyTypeSchema>(HttpStatus.NOT_IMPLEMENTED);
244         }
245
246         public ResponseEntity<List<Integer>> getAllTypes() {
247                 log.info("getAllTypes");
248                 
249                 String accept = request.getHeader("Accept");
250                 if (accept != null && accept.contains("application/json")) {
251                         try {
252                                 Set<String> types = policyTypes.keySet();
253                                 String res = "";
254                                 for (Iterator<String> iterator = types.iterator(); iterator.hasNext();) {
255                                         String tid = (String) iterator.next();
256                                         if (res.length() > 0) {
257                                                 res = res + ",";
258                                         }
259                                         res = res + tid;
260                                 }
261                                 return new ResponseEntity<List<Integer>>(objectMapper.readValue("[" + res + "]", List.class),
262                                                 HttpStatus.OK);
263                         } catch (IOException e) {
264                                 e.printStackTrace();
265                                 log.info("getAllTypes - Couldn't serialize response for content type application/json");
266                                 return new ResponseEntity<List<Integer>>(HttpStatus.INTERNAL_SERVER_ERROR);
267                         }
268                 }
269                 log.info("getAllTypes - not implemented");
270                 return new ResponseEntity<List<Integer>>(HttpStatus.NOT_IMPLEMENTED);
271         }
272
273         public ResponseEntity<Void> createReplaceInstance(Integer policyTypeId, String policyInstanceId, Object body) {
274                 log.info("createReplaceInstance -  policyTypeId:" + policyTypeId);
275                 log.info("createReplaceInstance -  policyInstanceId:" + policyInstanceId);
276                 log.info("createReplaceInstance -  body:" + body);
277
278                 if (policyTypeId == null || policyInstanceId == null || body == null) {
279                         log.info("createReplaceInstance - bad parameter");
280                         return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
281                 }
282
283                 log.info("createReplaceInstance -  bodyclass:" + body.getClass().toString());
284
285                 PolicyType policyType = policyTypes.get(policyTypeId.toString());
286
287                 if (policyType == null) {
288                         log.info("createReplaceInstance - policytype does not exists");
289                         return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
290                 }
291
292                 // Create json string from schema
293                 String createSchema = null;
294                 try {
295                         PolicyTypeSchema schema = policyType.getSchema();
296                         // Convert Map to JSON
297                         String json = objectMapper.writeValueAsString(schema);
298                         // Print JSON output
299                         log.info("createReplaceInstance - schema - json: " + json);
300                         createSchema = objectMapper.writeValueAsString(schema.getCreateSchema());
301                         log.info("createReplaceInstance - createSchema - string: " + createSchema);
302                 } catch (Exception e) {
303                         e.printStackTrace();
304                         log.info("createReplaceInstance - schema corrupt");
305                         return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
306                 }
307
308                 // Create json string from instance
309                 String jsonInstance = null;
310                 try {
311                         log.info("createReplaceInstance - raw: " + body);
312                         // Convert Map to JSON
313                         jsonInstance = objectMapper.writeValueAsString(body);
314                         // Print JSON output
315                         log.info("createReplaceInstance - instance: " + jsonInstance);
316
317                 } catch (Exception e) {
318                         e.printStackTrace();
319                         log.info("createReplaceInstance - instancce corrupt");
320                         return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
321                 }
322
323                 if (!validateSchema(jsonInstance, createSchema)) {
324                         log.info("createReplaceInstance - schema validation failed");
325                         return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
326                 }
327                 PolicyInstance policyInstance = new PolicyInstance(policyInstanceId, body);
328                 policyType.createReplaceInstance(policyInstanceId, policyInstance);
329
330                 log.info("createReplaceInstance - created/replaced ok");
331                 return new ResponseEntity<Void>(HttpStatus.CREATED);
332
333         }
334
335         public ResponseEntity<List<String>> getAllInstanceForType(Integer policyTypeId) {
336                 log.info("getAllInstanceForType -  policyTypeId:" + policyTypeId);
337
338                 if (policyTypeId == null) {
339                         log.info("getAllInstanceForType - bad parameter");
340                         return new ResponseEntity<List<String>>(HttpStatus.NOT_FOUND);
341                 }
342
343                 String accept = request.getHeader("Accept");
344                 if (accept != null && accept.contains("application/json")) {
345                         try {
346                                 PolicyType policyType = policyTypes.get(policyTypeId.toString());
347                                 if (policyType == null) {
348                                         log.info("getAllInstanceForType - policytype does not exists");
349                                         return new ResponseEntity<List<String>>(HttpStatus.NOT_FOUND);
350                                 }
351                                 Set<String> instances = policyType.getInstances();
352                                 String res = "";
353                                 for (Iterator iterator = instances.iterator(); iterator.hasNext();) {
354                                         String iid = (String) iterator.next();
355                                         iid = "\"" + iid + "\"";
356                                         if (res.length() > 0) {
357                                                 res = res + ",";
358                                         }
359                                         res = res + iid;
360                                 }
361                                 log.info("getAllInstanceForType - " + res);
362                                 return new ResponseEntity<List<String>>(objectMapper.readValue("[" + res + "]", List.class),
363                                                 HttpStatus.OK);
364                         } catch (IOException e) {
365                                 e.printStackTrace();
366                                 log.info("getAllInstanceForType - Couldn't serialize response for content type application/json");
367                                 return new ResponseEntity<List<String>>(HttpStatus.INTERNAL_SERVER_ERROR);
368                         }
369                 }
370                 log.info("getAllInstanceForType - not implemented");
371                 return new ResponseEntity<List<String>>(HttpStatus.NOT_IMPLEMENTED);
372
373         }
374
375         public ResponseEntity<Object> getPolicyInstance(Integer policyTypeId, String policyInstanceId) {
376                 log.info("getPolicyInstance -  policyTypeId:" + policyTypeId);
377                 log.info("getPolicyInstance -  policyInstanceId:" + policyInstanceId);
378
379                 if (policyTypeId == null || policyInstanceId == null) {
380                         log.info("getPolicyInstance - bad parameter");
381                         return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
382                 }
383
384                 String accept = request.getHeader("Accept");
385                 if (accept != null && accept.contains("application/json")) {
386                         try {
387                                 PolicyType policyType = policyTypes.get(policyTypeId.toString());
388                                 if (policyType == null) {
389                                         log.info("getPolicyInstance - policytype does not exists");
390                                         return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
391                                 }
392                                 PolicyInstance policyInstance = policyType.getInstance(policyInstanceId);
393                                 if (policyInstance == null) {
394                                         log.info("getPolicyInstance - policyinstance does not exists");
395                                         return new ResponseEntity<Object>(HttpStatus.NOT_FOUND);
396                                 }
397
398                                 String json = null;
399                                 try {
400                                         log.info("getPolicyInstance - rawschema: " + policyInstance.getJson());
401                                         // Convert Map to JSON
402                                         json = objectMapper.writeValueAsString(policyInstance.getJson());
403                                         // Print JSON output
404                                         log.info("getPolicyInstance - schema: " + json);
405
406                                 } catch (Exception e) {
407                                         e.printStackTrace();
408                                         log.info("getPolicyInstance - schema corrupt");
409                                         return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR);
410                                 }
411
412                                 return new ResponseEntity<Object>(objectMapper.readValue(json, Object.class), HttpStatus.OK);
413                         } catch (IOException e) {
414                                 e.printStackTrace();
415                                 log.info("getPolicyInstance - policyinstance corrupt");
416                                 return new ResponseEntity<Object>(HttpStatus.INTERNAL_SERVER_ERROR);
417                         }
418                 }
419
420                 return new ResponseEntity<Object>(HttpStatus.NOT_IMPLEMENTED);
421         }
422
423         public ResponseEntity<List<InlineResponse200>> getStatus(Integer policyTypeId, String policyInstanceId) {
424                 log.info("getStatus -  policyTypeId:" + policyTypeId);
425                 log.info("getStatus -  policyInstanceId:" + policyInstanceId);
426
427                 if (policyTypeId == null || policyInstanceId == null) {
428                         log.info("getStatus - bad parameters");
429                         return new ResponseEntity<List<InlineResponse200>>(HttpStatus.NOT_FOUND);
430                 }
431
432                 String accept = request.getHeader("Accept");
433                 if (accept != null && accept.contains("application/json")) {
434                         try {
435                                 PolicyType policyType = policyTypes.get(policyTypeId.toString());
436                                 if (policyType == null) {
437                                         log.info("getStatus - policytype does not exists");
438                                         return new ResponseEntity<List<InlineResponse200>>(HttpStatus.NOT_FOUND);
439                                 }
440                                 PolicyInstance policyInstance = policyType.getInstance(policyInstanceId);
441                                 if (policyInstance == null) {
442                                         log.info("getStatus - policyinstance does not exists");
443                                         return new ResponseEntity<List<InlineResponse200>>(HttpStatus.NOT_FOUND);
444                                 }
445
446                                 return new ResponseEntity<List<InlineResponse200>>(
447                                                 objectMapper.readValue("[ {\n  \"handler_id\" : \"NearRTRIC-1\",\n  \"status\" : \"enforced\"\n} ]",
448                                                                 List.class),
449                                                 HttpStatus.OK);
450                         } catch (IOException e) {
451                                 e.printStackTrace();
452                                 log.info("getStatus - Couldn't serialize response for content type application/json");
453                                 return new ResponseEntity<List<InlineResponse200>>(HttpStatus.INTERNAL_SERVER_ERROR);
454                         }
455                 }
456
457                 return new ResponseEntity<List<InlineResponse200>>(HttpStatus.NOT_IMPLEMENTED);
458         }
459
460 }