Some changes in status notifications
[nonrtric.git] / enrichment-coordinator-service / src / main / java / org / oransc / enrichment / controllers / consumer / ConsumerController.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2020 Nordix Foundation
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.util.ArrayList;
34 import java.util.Collection;
35 import java.util.List;
36 import java.util.Vector;
37
38 import org.everit.json.schema.Schema;
39 import org.everit.json.schema.loader.SchemaLoader;
40 import org.json.JSONObject;
41 import org.oransc.enrichment.configuration.ApplicationConfig;
42 import org.oransc.enrichment.controllers.ErrorResponse;
43 import org.oransc.enrichment.controllers.VoidResponse;
44 import org.oransc.enrichment.controllers.producer.ProducerCallbacks;
45 import org.oransc.enrichment.exceptions.ServiceException;
46 import org.oransc.enrichment.repository.EiJob;
47 import org.oransc.enrichment.repository.EiJobs;
48 import org.oransc.enrichment.repository.EiProducer;
49 import org.oransc.enrichment.repository.EiType;
50 import org.oransc.enrichment.repository.EiTypes;
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.RequestMapping;
61 import org.springframework.web.bind.annotation.RequestParam;
62 import org.springframework.web.bind.annotation.RestController;
63 import reactor.core.publisher.Mono;
64
65 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
66 @RestController("ConsumerController")
67 @Api(tags = {ConsumerConsts.CONSUMER_API_NAME})
68 @RequestMapping(path = ConsumerConsts.API_ROOT, produces = MediaType.APPLICATION_JSON_VALUE)
69 public class ConsumerController {
70
71     @Autowired
72     ApplicationConfig applicationConfig;
73
74     @Autowired
75     private EiJobs eiJobs;
76
77     @Autowired
78     private EiTypes eiTypes;
79
80     @Autowired
81     ProducerCallbacks producerCallbacks;
82
83     private static Gson gson = new GsonBuilder().create();
84
85     @GetMapping(path = "/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 = "/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             this.eiTypes.getType(eiTypeId); // Make sure that the type exists
118             ConsumerEiTypeInfo info = toEiTypeInfo();
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(path = "/eijobs", produces = MediaType.APPLICATION_JSON_VALUE)
126     @ApiOperation(value = "EI job identifiers", notes = "query for EI job identifiers")
127     @ApiResponses(
128         value = { //
129             @ApiResponse(
130                 code = 200,
131                 message = "EI job identifiers",
132                 response = String.class,
133                 responseContainer = "List"), //
134             @ApiResponse(
135                 code = 404,
136                 message = "Enrichment Information type is not found",
137                 response = ErrorResponse.ErrorInfo.class)})
138     public ResponseEntity<Object> getEiJobIds( //
139         @ApiParam(
140             name = ConsumerConsts.EI_TYPE_ID_PARAM,
141             required = false, //
142             value = ConsumerConsts.EI_TYPE_ID_PARAM_DESCRIPTION) //
143         @RequestParam(name = ConsumerConsts.EI_TYPE_ID_PARAM, required = false) String eiTypeId,
144         @ApiParam(
145             name = ConsumerConsts.OWNER_PARAM,
146             required = false, //
147             value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
148         @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
149         try {
150             List<String> result = new ArrayList<>();
151             if (owner != null) {
152                 for (EiJob job : this.eiJobs.getJobsForOwner(owner)) {
153                     if (eiTypeId == null || job.getTypeId().equals(eiTypeId)) {
154                         result.add(job.getId());
155                     }
156                 }
157             } else if (eiTypeId != null) {
158                 this.eiJobs.getJobsForType(eiTypeId).forEach(job -> result.add(job.getId()));
159             } else {
160                 this.eiJobs.getJobs().forEach(job -> result.add(job.getId()));
161             }
162             return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
163         } catch (
164
165         Exception e) {
166             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
167         }
168     }
169
170     @GetMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
171     @ApiOperation(value = "Individual EI job", notes = "")
172     @ApiResponses(
173         value = { //
174             @ApiResponse(code = 200, message = "EI job", response = ConsumerEiJobInfo.class), //
175             @ApiResponse(
176                 code = 404,
177                 message = "Enrichment Information job is not found",
178                 response = ErrorResponse.ErrorInfo.class)})
179     public ResponseEntity<Object> getIndividualEiJob( //
180         @PathVariable("eiJobId") String eiJobId) {
181         try {
182             EiJob job = this.eiJobs.getJob(eiJobId);
183             return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
184         } catch (Exception e) {
185             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
186         }
187     }
188
189     @GetMapping(path = "/eijobs/{eiJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
190     @ApiOperation(value = "EI job status", notes = "")
191     @ApiResponses(
192         value = { //
193             @ApiResponse(code = 200, message = "EI job status", response = ConsumerEiJobStatus.class), //
194             @ApiResponse(
195                 code = 404,
196                 message = "Enrichment Information job is not found",
197                 response = ErrorResponse.ErrorInfo.class)})
198     public ResponseEntity<Object> getEiJobStatus( //
199         @PathVariable("eiJobId") String eiJobId) {
200         try {
201             EiJob job = this.eiJobs.getJob(eiJobId);
202             return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
203         } catch (Exception e) {
204             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
205         }
206     }
207
208     private Collection<EiProducer> getProducers(EiJob eiJob) {
209         try {
210             return this.eiTypes.getType(eiJob.getTypeId()).getProducers();
211         } catch (Exception e) {
212             return new Vector<>();
213         }
214     }
215
216     private ConsumerEiJobStatus toEiJobStatus(EiJob job) {
217         if (getProducers(job).isEmpty()) {
218             return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.DISABLED);
219         } else {
220             return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.ENABLED);
221         }
222     }
223
224     @DeleteMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
225     @ApiOperation(value = "Individual EI job", notes = "")
226     @ApiResponses(
227         value = { //
228             @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
229             @ApiResponse(code = 204, message = "Job deleted", response = VoidResponse.class),
230             @ApiResponse(
231                 code = 404,
232                 message = "Enrichment Information job is not found",
233                 response = ErrorResponse.ErrorInfo.class)})
234     public ResponseEntity<Object> deleteIndividualEiJob( //
235         @PathVariable("eiJobId") String eiJobId) {
236         try {
237             EiJob job = this.eiJobs.getJob(eiJobId);
238             this.eiJobs.remove(job);
239             this.producerCallbacks.notifyProducersJobDeleted(job);
240             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
241         } catch (Exception e) {
242             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
243         }
244     }
245
246     @PutMapping(
247         path = "/eijobs/{eiJobId}", //
248         produces = MediaType.APPLICATION_JSON_VALUE, //
249         consumes = MediaType.APPLICATION_JSON_VALUE)
250     @ApiOperation(value = "Individual EI job", notes = "")
251     @ApiResponses(
252         value = { //
253             @ApiResponse(code = 201, message = "Job created", response = VoidResponse.class), //
254             @ApiResponse(code = 200, message = "Job updated", response = VoidResponse.class), // ,
255             @ApiResponse(
256                 code = 404,
257                 message = "Enrichment Information type is not found",
258                 response = ErrorResponse.ErrorInfo.class)})
259     public Mono<ResponseEntity<Object>> putIndividualEiJob( //
260         @PathVariable("eiJobId") String eiJobId, //
261         @RequestBody ConsumerEiJobInfo eiJobObject) {
262
263         final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
264
265         return validatePutEiJob(eiJobId, eiJobObject) //
266             .flatMap(this::notifyProducersNewJob) //
267             .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
268             .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
269             .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
270     }
271
272     private Mono<EiJob> notifyProducersNewJob(EiJob newEiJob) {
273         return this.producerCallbacks.notifyProducersJobStarted(newEiJob) //
274             .flatMap(noOfAcceptingProducers -> {
275                 if (noOfAcceptingProducers.intValue() > 0) {
276                     return Mono.just(newEiJob);
277                 } else {
278                     return Mono.error(new ServiceException("Job not accepted by any producers", HttpStatus.CONFLICT));
279                 }
280             });
281     }
282
283     private Mono<EiJob> validatePutEiJob(String eiJobId, ConsumerEiJobInfo eiJobInfo) {
284         try {
285             EiType eiType = this.eiTypes.getType(eiJobInfo.eiTypeId);
286             validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobData);
287             EiJob existingEiJob = this.eiJobs.get(eiJobId);
288
289             if (existingEiJob != null && !existingEiJob.getTypeId().equals(eiJobInfo.eiTypeId)) {
290                 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
291             }
292             return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
293         } catch (Exception e) {
294             return Mono.error(e);
295         }
296     }
297
298     private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
299         if (schemaObj != null) { // schema is optional for now
300             try {
301                 ObjectMapper mapper = new ObjectMapper();
302
303                 String schemaAsString = mapper.writeValueAsString(schemaObj);
304                 JSONObject schemaJSON = new JSONObject(schemaAsString);
305                 Schema schema = SchemaLoader.load(schemaJSON);
306
307                 String objectAsString = mapper.writeValueAsString(object);
308                 JSONObject json = new JSONObject(objectAsString);
309                 schema.validate(json);
310             } catch (Exception e) {
311                 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
312             }
313         }
314     }
315
316     private EiJob toEiJob(ConsumerEiJobInfo info, String id, EiType type) {
317         return new EiJob(id, //
318             type.getId(), //
319             info.owner, //
320             info.jobData, //
321             info.targetUri, //
322             info.statusNotificationUri == null ? "" : info.statusNotificationUri);
323     }
324
325     private ConsumerEiTypeInfo toEiTypeInfo() {
326         return new ConsumerEiTypeInfo();
327     }
328
329     private ConsumerEiJobInfo toEiJobInfo(EiJob s) {
330         return new ConsumerEiJobInfo(s.getTypeId(), s.getJobData(), s.getOwner(), s.getTargetUrl(),
331             s.getJobStatusUrl());
332     }
333 }