6e9438d3d8d7a37666aee93424f4a748daddb11a
[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
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.configuration.ApplicationConfig;
41 import org.oransc.enrichment.controllers.ErrorResponse;
42 import org.oransc.enrichment.controllers.VoidResponse;
43 import org.oransc.enrichment.controllers.producer.ProducerCallbacks;
44 import org.oransc.enrichment.exceptions.ServiceException;
45 import org.oransc.enrichment.repository.EiJob;
46 import org.oransc.enrichment.repository.EiJobs;
47 import org.oransc.enrichment.repository.EiProducer;
48 import org.oransc.enrichment.repository.EiProducers;
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     private EiProducers eiProducers;
82
83     @Autowired
84     ProducerCallbacks producerCallbacks;
85
86     private static Gson gson = new GsonBuilder().create();
87
88     @GetMapping(path = "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
89     @ApiOperation(value = "EI type identifiers", notes = "")
90     @ApiResponses(
91         value = { //
92             @ApiResponse(
93                 code = 200,
94                 message = "EI type identifiers",
95                 response = String.class,
96                 responseContainer = "List"), //
97         })
98     public ResponseEntity<Object> getEiTypeIdentifiers( //
99     ) {
100         List<String> result = new ArrayList<>();
101         for (EiType eiType : this.eiTypes.getAllEiTypes()) {
102             result.add(eiType.getId());
103         }
104
105         return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
106     }
107
108     @GetMapping(path = "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
109     @ApiOperation(value = "Individual EI type", notes = "")
110     @ApiResponses(
111         value = { //
112             @ApiResponse(code = 200, message = "EI type", response = ConsumerEiTypeInfo.class), //
113             @ApiResponse(
114                 code = 404,
115                 message = "Enrichment Information type is not found",
116                 response = ErrorResponse.ErrorInfo.class)})
117     public ResponseEntity<Object> getEiType( //
118         @PathVariable("eiTypeId") String eiTypeId) {
119         try {
120             this.eiTypes.getType(eiTypeId); // Make sure that the type exists
121             ConsumerEiTypeInfo info = toEiTypeInfo();
122             return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
123         } catch (Exception e) {
124             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
125         }
126     }
127
128     @GetMapping(path = "/eijobs", produces = MediaType.APPLICATION_JSON_VALUE)
129     @ApiOperation(value = "EI job identifiers", notes = "query for EI job identifiers")
130     @ApiResponses(
131         value = { //
132             @ApiResponse(
133                 code = 200,
134                 message = "EI job identifiers",
135                 response = String.class,
136                 responseContainer = "List"), //
137             @ApiResponse(
138                 code = 404,
139                 message = "Enrichment Information type is not found",
140                 response = ErrorResponse.ErrorInfo.class)})
141     public ResponseEntity<Object> getEiJobIds( //
142         @ApiParam(
143             name = ConsumerConsts.EI_TYPE_ID_PARAM,
144             required = false, //
145             value = ConsumerConsts.EI_TYPE_ID_PARAM_DESCRIPTION) //
146         @RequestParam(name = ConsumerConsts.EI_TYPE_ID_PARAM, required = false) String eiTypeId,
147         @ApiParam(
148             name = ConsumerConsts.OWNER_PARAM,
149             required = false, //
150             value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
151         @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
152         try {
153             List<String> result = new ArrayList<>();
154             if (owner != null) {
155                 for (EiJob job : this.eiJobs.getJobsForOwner(owner)) {
156                     if (eiTypeId == null || job.getTypeId().equals(eiTypeId)) {
157                         result.add(job.getId());
158                     }
159                 }
160             } else if (eiTypeId != null) {
161                 this.eiJobs.getJobsForType(eiTypeId).forEach(job -> result.add(job.getId()));
162             } else {
163                 this.eiJobs.getJobs().forEach(job -> result.add(job.getId()));
164             }
165             return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
166         } catch (
167
168         Exception e) {
169             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
170         }
171     }
172
173     @GetMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
174     @ApiOperation(value = "Individual EI job", notes = "")
175     @ApiResponses(
176         value = { //
177             @ApiResponse(code = 200, message = "EI job", response = ConsumerEiJobInfo.class), //
178             @ApiResponse(
179                 code = 404,
180                 message = "Enrichment Information job is not found",
181                 response = ErrorResponse.ErrorInfo.class)})
182     public ResponseEntity<Object> getIndividualEiJob( //
183         @PathVariable("eiJobId") String eiJobId) {
184         try {
185             EiJob job = this.eiJobs.getJob(eiJobId);
186             return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
187         } catch (Exception e) {
188             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
189         }
190     }
191
192     @GetMapping(path = "/eijobs/{eiJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
193     @ApiOperation(value = "EI job status", notes = "")
194     @ApiResponses(
195         value = { //
196             @ApiResponse(code = 200, message = "EI job status", response = ConsumerEiJobStatus.class), //
197             @ApiResponse(
198                 code = 404,
199                 message = "Enrichment Information job is not found",
200                 response = ErrorResponse.ErrorInfo.class)})
201     public ResponseEntity<Object> getEiJobStatus( //
202         @PathVariable("eiJobId") String eiJobId) {
203         try {
204             EiJob job = this.eiJobs.getJob(eiJobId);
205             return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
206         } catch (Exception e) {
207             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
208         }
209     }
210
211     private Collection<EiProducer> getProducers(EiJob eiJob) {
212         return this.eiProducers.getProducersForType(eiJob.getTypeId());
213     }
214
215     private ConsumerEiJobStatus toEiJobStatus(EiJob job) {
216         if (getProducers(job).isEmpty()) {
217             return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.DISABLED);
218         } else {
219             return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.ENABLED);
220         }
221     }
222
223     @DeleteMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
224     @ApiOperation(value = "Individual EI job", notes = "")
225     @ApiResponses(
226         value = { //
227             @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
228             @ApiResponse(code = 204, message = "Job deleted", response = VoidResponse.class),
229             @ApiResponse(
230                 code = 404,
231                 message = "Enrichment Information job is not found",
232                 response = ErrorResponse.ErrorInfo.class)})
233     public ResponseEntity<Object> deleteIndividualEiJob( //
234         @PathVariable("eiJobId") String eiJobId) {
235         try {
236             EiJob job = this.eiJobs.getJob(eiJobId);
237             this.eiJobs.remove(job, this.eiProducers);
238             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
239         } catch (Exception e) {
240             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
241         }
242     }
243
244     @PutMapping(
245         path = "/eijobs/{eiJobId}", //
246         produces = MediaType.APPLICATION_JSON_VALUE, //
247         consumes = MediaType.APPLICATION_JSON_VALUE)
248     @ApiOperation(value = "Individual EI job", notes = "")
249     @ApiResponses(
250         value = { //
251             @ApiResponse(code = 201, message = "Job created", response = VoidResponse.class), //
252             @ApiResponse(code = 200, message = "Job updated", response = VoidResponse.class), // ,
253             @ApiResponse(
254                 code = 404,
255                 message = "Enrichment Information type is not found",
256                 response = ErrorResponse.ErrorInfo.class)})
257     public Mono<ResponseEntity<Object>> putIndividualEiJob( //
258         @PathVariable("eiJobId") String eiJobId, //
259         @RequestBody ConsumerEiJobInfo eiJobObject) {
260
261         final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
262
263         return validatePutEiJob(eiJobId, eiJobObject) //
264             .flatMap(this::startEiJob) //
265             .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
266             .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
267             .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
268     }
269
270     private Mono<EiJob> startEiJob(EiJob newEiJob) {
271         return this.producerCallbacks.startEiJob(newEiJob, eiProducers) //
272             .flatMap(noOfAcceptingProducers -> {
273                 if (noOfAcceptingProducers.intValue() > 0) {
274                     return Mono.just(newEiJob);
275                 } else {
276                     return Mono.error(new ServiceException("Job not accepted by any producers", HttpStatus.CONFLICT));
277                 }
278             });
279     }
280
281     private Mono<EiJob> validatePutEiJob(String eiJobId, ConsumerEiJobInfo eiJobInfo) {
282         try {
283             EiType eiType = this.eiTypes.getType(eiJobInfo.eiTypeId);
284             validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobData);
285             EiJob existingEiJob = this.eiJobs.get(eiJobId);
286
287             if (existingEiJob != null && !existingEiJob.getTypeId().equals(eiJobInfo.eiTypeId)) {
288                 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
289             }
290             return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
291         } catch (Exception e) {
292             return Mono.error(e);
293         }
294     }
295
296     private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
297         if (schemaObj != null) { // schema is optional for now
298             try {
299                 ObjectMapper mapper = new ObjectMapper();
300
301                 String schemaAsString = mapper.writeValueAsString(schemaObj);
302                 JSONObject schemaJSON = new JSONObject(schemaAsString);
303                 Schema schema = SchemaLoader.load(schemaJSON);
304
305                 String objectAsString = mapper.writeValueAsString(object);
306                 JSONObject json = new JSONObject(objectAsString);
307                 schema.validate(json);
308             } catch (Exception e) {
309                 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
310             }
311         }
312     }
313
314     private EiJob toEiJob(ConsumerEiJobInfo info, String id, EiType type) {
315         return EiJob.builder() //
316             .id(id) //
317             .typeId(type.getId()) //
318             .owner(info.owner) //
319             .jobData(info.jobData) //
320             .targetUrl(info.targetUri) //
321             .jobStatusUrl(info.statusNotificationUri == null ? "" : info.statusNotificationUri) //
322             .build();
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 }