39796ee1a2c7703718653d8f68e9dea5a2440577
[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.List;
35
36 import org.everit.json.schema.Schema;
37 import org.everit.json.schema.loader.SchemaLoader;
38 import org.json.JSONObject;
39 import org.oransc.enrichment.clients.ProducerCallbacks;
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.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.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.http.HttpStatus;
51 import org.springframework.http.MediaType;
52 import org.springframework.http.ResponseEntity;
53 import org.springframework.web.bind.annotation.DeleteMapping;
54 import org.springframework.web.bind.annotation.GetMapping;
55 import org.springframework.web.bind.annotation.PathVariable;
56 import org.springframework.web.bind.annotation.PutMapping;
57 import org.springframework.web.bind.annotation.RequestBody;
58 import org.springframework.web.bind.annotation.RequestParam;
59 import org.springframework.web.bind.annotation.RestController;
60 import reactor.core.publisher.Mono;
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     @Autowired
68     ApplicationConfig applicationConfig;
69
70     @Autowired
71     private EiJobs eiJobs;
72
73     @Autowired
74     private EiTypes eiTypes;
75
76     @Autowired
77     ProducerCallbacks producerCallbacks;
78
79     private static Gson gson = new GsonBuilder() //
80         .serializeNulls() //
81         .create(); //
82
83     @GetMapping(path = ConsumerConsts.API_ROOT + "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
84     @ApiOperation(value = "EI type identifiers", notes = "")
85     @ApiResponses(
86         value = { //
87             @ApiResponse(
88                 code = 200,
89                 message = "EI type identifiers",
90                 response = String.class,
91                 responseContainer = "List"), //
92         })
93     public ResponseEntity<Object> getEiTypeIdentifiers( //
94     ) {
95         List<String> result = new ArrayList<>();
96         for (EiType eiType : this.eiTypes.getAllEiTypes()) {
97             result.add(eiType.getId());
98         }
99
100         return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
101     }
102
103     @GetMapping(path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
104     @ApiOperation(value = "Individual EI type", notes = "")
105     @ApiResponses(
106         value = { //
107             @ApiResponse(code = 200, message = "EI type", response = ConsumerEiTypeInfo.class), //
108             @ApiResponse(
109                 code = 404,
110                 message = "Enrichment Information type is not found",
111                 response = ErrorResponse.ErrorInfo.class)})
112     public ResponseEntity<Object> getEiType( //
113         @PathVariable("eiTypeId") String eiTypeId) {
114         try {
115             EiType t = this.eiTypes.getType(eiTypeId);
116             ConsumerEiTypeInfo info = toEiTypeInfo(t);
117             return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
118         } catch (Exception e) {
119             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
120         }
121     }
122
123     @GetMapping(
124         path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs",
125         produces = MediaType.APPLICATION_JSON_VALUE)
126     @ApiOperation(value = "EI job identifiers", notes = "")
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         @PathVariable("eiTypeId") String eiTypeId, //
140         @ApiParam(
141             name = ConsumerConsts.OWNER_PARAM,
142             required = false, //
143             value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
144         @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
145         try {
146             this.eiTypes.getType(eiTypeId); // Just to check that the type exists
147             List<String> result = new ArrayList<>();
148             if (owner != null) {
149                 for (EiJob job : this.eiJobs.getJobsForOwner(owner)) {
150                     if (eiTypeId == null || job.type().getId().equals(eiTypeId)) {
151                         result.add(job.id());
152                     }
153                 }
154             } else {
155                 for (EiJob job : this.eiJobs.getJobsForType(eiTypeId)) {
156                     result.add(job.id());
157                 }
158             }
159             return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
160         } catch (Exception e) {
161             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
162         }
163     }
164
165     @GetMapping(
166         path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}",
167         produces = MediaType.APPLICATION_JSON_VALUE)
168     @ApiOperation(value = "Individual EI Job", notes = "")
169     @ApiResponses(
170         value = { //
171             @ApiResponse(code = 200, message = "EI Job", response = ConsumerEiJobInfo.class), //
172             @ApiResponse(
173                 code = 404,
174                 message = "Enrichment Information type or job is not found",
175                 response = ErrorResponse.ErrorInfo.class)})
176     public ResponseEntity<Object> getIndividualEiJob( //
177         @PathVariable("eiTypeId") String eiTypeId, //
178         @PathVariable("eiJobId") String eiJobId) {
179         try {
180             this.eiTypes.getType(eiTypeId); // Just to check that the type exists
181             EiJob job = this.eiJobs.getJob(eiJobId);
182             return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
183         } catch (Exception e) {
184             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
185         }
186     }
187
188     @GetMapping(
189         path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}/status",
190         produces = MediaType.APPLICATION_JSON_VALUE)
191     @ApiOperation(value = "EI Job status", notes = "")
192     @ApiResponses(
193         value = { //
194             @ApiResponse(code = 200, message = "EI Job status", response = ConsumerEiJobStatus.class), //
195             @ApiResponse(
196                 code = 404,
197                 message = "Enrichment Information type or job is not found",
198                 response = ErrorResponse.ErrorInfo.class)})
199     public ResponseEntity<Object> getEiJobStatus( //
200         @PathVariable("eiTypeId") String eiTypeId, //
201         @PathVariable("eiJobId") String eiJobId) {
202         try {
203             this.eiTypes.getType(eiTypeId); // Just to check that the type exists
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 ConsumerEiJobStatus toEiJobStatus(EiJob job) {
212         // TODO
213         return new ConsumerEiJobStatus(ConsumerEiJobStatus.OperationalState.ENABLED);
214     }
215
216     @DeleteMapping(
217         path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}",
218         produces = MediaType.APPLICATION_JSON_VALUE)
219     @ApiOperation(value = "Individual EI Job", notes = "")
220     @ApiResponses(
221         value = { //
222             @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
223             @ApiResponse(code = 204, message = "Job deleted", response = VoidResponse.class),
224             @ApiResponse(
225                 code = 404,
226                 message = "Enrichment Information type or job is not found",
227                 response = ErrorResponse.ErrorInfo.class)})
228     public ResponseEntity<Object> deleteIndividualEiJob( //
229         @PathVariable("eiTypeId") String eiTypeId, //
230         @PathVariable("eiJobId") String eiJobId) {
231         try {
232             EiJob job = this.eiJobs.getJob(eiJobId);
233             this.eiJobs.remove(job);
234             this.producerCallbacks.notifyProducersJobDeleted(job);
235             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
236         } catch (Exception e) {
237             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
238         }
239     }
240
241     @PutMapping(
242         path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}", //
243         produces = MediaType.APPLICATION_JSON_VALUE, //
244         consumes = MediaType.APPLICATION_JSON_VALUE)
245     @ApiOperation(value = "Individual EI Job", notes = "")
246     @ApiResponses(
247         value = { //
248             @ApiResponse(code = 201, message = "Job created", response = VoidResponse.class), //
249             @ApiResponse(code = 200, message = "Job updated", response = VoidResponse.class), // ,
250             @ApiResponse(
251                 code = 404,
252                 message = "Enrichment Information type is not found",
253                 response = ErrorResponse.ErrorInfo.class)})
254     public Mono<ResponseEntity<Object>> putIndividualEiJob( //
255         @PathVariable("eiTypeId") String eiTypeId, //
256         @PathVariable("eiJobId") String eiJobId, //
257         @RequestBody ConsumerEiJobInfo eiJobInfo) {
258
259         final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
260
261         return validatePutEiJob(eiTypeId, eiJobId, eiJobInfo) //
262             .flatMap(this::notifyProducersNewJob) //
263             .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
264             .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
265             .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
266     }
267
268     private Mono<EiJob> notifyProducersNewJob(EiJob newEiJob) {
269         return this.producerCallbacks.notifyProducersJobStarted(newEiJob) //
270             .flatMap(noOfAcceptingProducers -> {
271                 if (noOfAcceptingProducers.intValue() > 0) {
272                     return Mono.just(newEiJob);
273                 } else {
274                     return Mono.error(new ServiceException("Job not accepted by any producers", HttpStatus.CONFLICT));
275                 }
276             });
277     }
278
279     private Mono<EiJob> validatePutEiJob(String eiTypeId, String eiJobId, ConsumerEiJobInfo eiJobInfo) {
280         try {
281             EiType eiType = this.eiTypes.getType(eiTypeId);
282             validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobData);
283             EiJob existingEiJob = this.eiJobs.get(eiJobId);
284
285             if (existingEiJob != null && !existingEiJob.type().getId().equals(eiTypeId)) {
286                 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
287             }
288             return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
289         } catch (Exception e) {
290             return Mono.error(e);
291         }
292     }
293
294     private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
295         if (schemaObj != null) { // schema is optional for now
296             try {
297                 ObjectMapper mapper = new ObjectMapper();
298
299                 String schemaAsString = mapper.writeValueAsString(schemaObj);
300                 JSONObject schemaJSON = new JSONObject(schemaAsString);
301                 Schema schema = SchemaLoader.load(schemaJSON);
302
303                 String objectAsString = mapper.writeValueAsString(object);
304                 JSONObject json = new JSONObject(objectAsString);
305                 schema.validate(json);
306             } catch (Exception e) {
307                 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
308             }
309         }
310     }
311
312     // Status TBD
313
314     private EiJob toEiJob(ConsumerEiJobInfo info, String id, EiType type) {
315         return ImmutableEiJob.builder() //
316             .id(id) //
317             .type(type) //
318             .owner(info.owner) //
319             .jobData(info.jobData) //
320             .targetUri(info.targetUri) //
321             .build();
322     }
323
324     private ConsumerEiTypeInfo toEiTypeInfo(EiType t) {
325         return new ConsumerEiTypeInfo(t.getJobDataSchema());
326     }
327
328     private ConsumerEiJobInfo toEiJobInfo(EiJob s) {
329         return new ConsumerEiJobInfo(s.jobData(), s.owner(), s.targetUri());
330     }
331 }