Merge "Added enrichment-coordinator-service module in nonrtric"
[nonrtric.git] / enrichment-coordinator-service / src / main / java / org / oransc / enrichment / controllers / consumer / ConsumerController.java
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2020 Nordix Foundation. 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.oransc.enrichment.controllers.consumer;
22
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26
27 import io.swagger.annotations.Api;
28 import io.swagger.annotations.ApiOperation;
29 import io.swagger.annotations.ApiParam;
30 import io.swagger.annotations.ApiResponse;
31 import io.swagger.annotations.ApiResponses;
32
33 import java.lang.invoke.MethodHandles;
34 import java.util.ArrayList;
35 import java.util.List;
36
37 import org.everit.json.schema.Schema;
38 import org.everit.json.schema.loader.SchemaLoader;
39 import org.json.JSONObject;
40 import org.oransc.enrichment.clients.ProducerCallbacks;
41 import org.oransc.enrichment.configuration.ApplicationConfig;
42 import org.oransc.enrichment.controllers.ErrorResponse;
43 import org.oransc.enrichment.exceptions.ServiceException;
44 import org.oransc.enrichment.repository.EiJob;
45 import org.oransc.enrichment.repository.EiJobs;
46 import org.oransc.enrichment.repository.EiType;
47 import org.oransc.enrichment.repository.EiTypes;
48 import org.oransc.enrichment.repository.ImmutableEiJob;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.http.HttpStatus;
53 import org.springframework.http.MediaType;
54 import org.springframework.http.ResponseEntity;
55 import org.springframework.web.bind.annotation.DeleteMapping;
56 import org.springframework.web.bind.annotation.GetMapping;
57 import org.springframework.web.bind.annotation.PathVariable;
58 import org.springframework.web.bind.annotation.PutMapping;
59 import org.springframework.web.bind.annotation.RequestBody;
60 import org.springframework.web.bind.annotation.RestController;
61
62 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
63 @RestController("ConsumerController")
64 @Api(tags = {ConsumerConsts.CONSUMER_API_NAME})
65 public class ConsumerController {
66
67     private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
68
69     @Autowired
70     ApplicationConfig applicationConfig;
71
72     @Autowired
73     private EiJobs eiJobs;
74
75     @Autowired
76     private EiTypes eiTypes;
77
78     @Autowired
79     ProducerCallbacks producerCallbacks;
80
81     private static Gson gson = new GsonBuilder() //
82         .serializeNulls() //
83         .create(); //
84
85     @GetMapping(path = ConsumerConsts.API_ROOT + "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
86     @ApiOperation(value = "EI type identifiers", notes = "")
87     @ApiResponses(
88         value = { //
89             @ApiResponse(
90                 code = 200,
91                 message = "EI type identifiers",
92                 response = String.class,
93                 responseContainer = "List"), //
94         })
95     public ResponseEntity<Object> getEiTypeIdentifiers( //
96     ) {
97         List<String> result = new ArrayList<>();
98         for (EiType eiType : this.eiTypes.getAllEiTypes()) {
99             result.add(eiType.getId());
100         }
101
102         return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
103     }
104
105     @GetMapping(path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
106     @ApiOperation(value = "Individual EI type", notes = "")
107     @ApiResponses(
108         value = { //
109             @ApiResponse(code = 200, message = "EI type", response = ConsumerEiTypeInfo.class), //
110             @ApiResponse(
111                 code = 404,
112                 message = "Enrichment Information type is not found",
113                 response = ErrorResponse.ErrorInfo.class)})
114     public ResponseEntity<Object> getEiType( //
115         @PathVariable("eiTypeId") String eiTypeId) {
116         try {
117             EiType t = this.eiTypes.getType(eiTypeId);
118             ConsumerEiTypeInfo info = toEiTypeInfo(t);
119             return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
120         } catch (Exception e) {
121             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
122         }
123     }
124
125     @GetMapping(
126         path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs",
127         produces = MediaType.APPLICATION_JSON_VALUE)
128     @ApiOperation(value = "EI job identifiers", notes = "")
129     @ApiResponses(
130         value = { //
131             @ApiResponse(
132                 code = 200,
133                 message = "EI job identifiers",
134                 response = String.class,
135                 responseContainer = "List"), //
136             @ApiResponse(
137                 code = 404,
138                 message = "Enrichment Information type is not found",
139                 response = ErrorResponse.ErrorInfo.class)})
140     public ResponseEntity<Object> getEiJobIds( //
141         @PathVariable("eiTypeId") String eiTypeId, //
142         @ApiParam(
143             name = ConsumerConsts.OWNER_PARAM,
144             required = false, //
145             value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
146         String owner) {
147         try {
148             this.eiTypes.getType(eiTypeId); // Just to check that the type exists
149             List<String> result = new ArrayList<>();
150             for (EiJob job : this.eiJobs.getJobsForType(eiTypeId)) {
151                 result.add(job.id());
152             }
153             return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
154         } catch (Exception e) {
155             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
156         }
157     }
158
159     @GetMapping(
160         path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}",
161         produces = MediaType.APPLICATION_JSON_VALUE)
162     @ApiOperation(value = "Individual EI Job", notes = "")
163     @ApiResponses(
164         value = { //
165             @ApiResponse(code = 200, message = "EI Job", response = ConsumerEiJobInfo.class), //
166             @ApiResponse(
167                 code = 404,
168                 message = "Enrichment Information type or job is not found",
169                 response = ErrorResponse.ErrorInfo.class)})
170     public ResponseEntity<Object> getIndividualEiJob( //
171         @PathVariable("eiTypeId") String eiTypeId, //
172         @PathVariable("eiJobId") String eiJobId) {
173         try {
174             this.eiTypes.getType(eiTypeId); // Just to check that the type exists
175             EiJob job = this.eiJobs.getJob(eiJobId);
176             return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
177         } catch (Exception e) {
178             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
179         }
180     }
181
182     @GetMapping(
183         path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}/status",
184         produces = MediaType.APPLICATION_JSON_VALUE)
185     @ApiOperation(value = "EI Job status", notes = "")
186     @ApiResponses(
187         value = { //
188             @ApiResponse(code = 200, message = "EI Job status", response = ConsumerEiJobStatus.class), //
189             @ApiResponse(
190                 code = 404,
191                 message = "Enrichment Information type or job is not found",
192                 response = ErrorResponse.ErrorInfo.class)})
193     public ResponseEntity<Object> getEiJobStatus( //
194         @PathVariable("eiTypeId") String eiTypeId, //
195         @PathVariable("eiJobId") String eiJobId) {
196         try {
197             this.eiTypes.getType(eiTypeId); // Just to check that the type exists
198             EiJob job = this.eiJobs.getJob(eiJobId);
199             return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
200         } catch (Exception e) {
201             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
202         }
203     }
204
205     private ConsumerEiJobStatus toEiJobStatus(EiJob job) {
206         // TODO
207         return new ConsumerEiJobStatus(ConsumerEiJobStatus.OperationalState.ENABLED);
208     }
209
210     @DeleteMapping(
211         path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}",
212         produces = MediaType.APPLICATION_JSON_VALUE)
213     @ApiOperation(value = "Individual EI Job", notes = "")
214     @ApiResponses(
215         value = { //
216             @ApiResponse(code = 200, message = "Not used", response = void.class),
217             @ApiResponse(code = 204, message = "Job deleted", response = void.class),
218             @ApiResponse(
219                 code = 404,
220                 message = "Enrichment Information type or job is not found",
221                 response = ErrorResponse.ErrorInfo.class)})
222     public ResponseEntity<Object> deleteIndividualEiJob( //
223         @PathVariable("eiTypeId") String eiTypeId, //
224         @PathVariable("eiJobId") String eiJobId) {
225         try {
226             EiJob job = this.eiJobs.getJob(eiJobId);
227             this.eiJobs.remove(job);
228             this.producerCallbacks.notifyProducersJobDeleted(job);
229             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
230         } catch (Exception e) {
231             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
232         }
233     }
234
235     @PutMapping(
236         path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}", //
237         produces = MediaType.APPLICATION_JSON_VALUE, //
238         consumes = MediaType.APPLICATION_JSON_VALUE)
239     @ApiOperation(value = "Individual EI Job", notes = "")
240     @ApiResponses(
241         value = { //
242             @ApiResponse(code = 201, message = "Job created", response = void.class), //
243             @ApiResponse(code = 200, message = "Job updated", response = void.class), // ,
244             @ApiResponse(
245                 code = 404,
246                 message = "Enrichment Information type is not found",
247                 response = ErrorResponse.ErrorInfo.class)})
248     public ResponseEntity<Object> putIndividualEiJob( //
249         @PathVariable("eiTypeId") String eiTypeId, //
250         @PathVariable("eiJobId") String eiJobId, //
251         @RequestBody ConsumerEiJobInfo eiJobInfo) {
252         try {
253             EiType eiType = this.eiTypes.getType(eiTypeId);
254             validateJobData(eiType.getJobDataSchema(), eiJobInfo.jobData);
255             final boolean newJob = this.eiJobs.get(eiJobId) == null;
256             EiJob eiJob = toEiJob(eiJobInfo, eiJobId, eiType);
257             this.eiJobs.put(eiJob);
258             this.producerCallbacks.notifyProducersJobCreated(eiJob);
259             return new ResponseEntity<>(newJob ? HttpStatus.CREATED : HttpStatus.OK);
260         } catch (Exception e) {
261             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
262         }
263     }
264
265     private void validateJobData(Object schemaObj, Object object) throws ServiceException {
266         if (schemaObj == null) {
267             return; // schema is optional for now
268         }
269         try {
270             ObjectMapper mapper = new ObjectMapper();
271
272             String schemaAsString = mapper.writeValueAsString(schemaObj);
273             JSONObject schemaJSON = new JSONObject(schemaAsString);
274             Schema schema = SchemaLoader.load(schemaJSON);
275
276             String objectAsString = mapper.writeValueAsString(object);
277             JSONObject json = new JSONObject(objectAsString);
278             schema.validate(json);
279         } catch (Exception e) {
280             throw new ServiceException("Json validation failure", e);
281         }
282
283     }
284
285     // Status TBD
286
287     private EiJob toEiJob(ConsumerEiJobInfo info, String id, EiType type) {
288         return ImmutableEiJob.builder() //
289             .id(id) //
290             .type(type) //
291             .owner(info.owner) //
292             .jobData(info.jobData) //
293             .build();
294     }
295
296     private ConsumerEiTypeInfo toEiTypeInfo(EiType t) {
297         return new ConsumerEiTypeInfo(t.getJobDataSchema());
298     }
299
300     private ConsumerEiJobInfo toEiJobInfo(EiJob s) {
301         return new ConsumerEiJobInfo(s.jobData(), s.owner());
302     }
303 }