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