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