NONRTRIC - 3PP dependency version update
[nonrtric.git] / information-coordinator-service / src / main / java / org / oransc / ics / controllers / a1e / A1eController.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.ics.controllers.a1e;
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.v3.oas.annotations.Operation;
28 import io.swagger.v3.oas.annotations.Parameter;
29 import io.swagger.v3.oas.annotations.media.ArraySchema;
30 import io.swagger.v3.oas.annotations.media.Content;
31 import io.swagger.v3.oas.annotations.media.Schema;
32 import io.swagger.v3.oas.annotations.responses.ApiResponse;
33 import io.swagger.v3.oas.annotations.responses.ApiResponses;
34 import io.swagger.v3.oas.annotations.tags.Tag;
35
36 import java.lang.invoke.MethodHandles;
37 import java.net.URI;
38 import java.net.URISyntaxException;
39 import java.util.ArrayList;
40 import java.util.List;
41
42 import org.json.JSONObject;
43 import org.oransc.ics.configuration.ApplicationConfig;
44 import org.oransc.ics.controllers.ErrorResponse;
45 import org.oransc.ics.controllers.VoidResponse;
46 import org.oransc.ics.controllers.r1producer.ProducerCallbacks;
47 import org.oransc.ics.exceptions.ServiceException;
48 import org.oransc.ics.repository.InfoJob;
49 import org.oransc.ics.repository.InfoJobs;
50 import org.oransc.ics.repository.InfoProducers;
51 import org.oransc.ics.repository.InfoType;
52 import org.oransc.ics.repository.InfoTypes;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.http.HttpStatus;
57 import org.springframework.http.MediaType;
58 import org.springframework.http.ResponseEntity;
59 import org.springframework.web.bind.annotation.DeleteMapping;
60 import org.springframework.web.bind.annotation.GetMapping;
61 import org.springframework.web.bind.annotation.PathVariable;
62 import org.springframework.web.bind.annotation.PutMapping;
63 import org.springframework.web.bind.annotation.RequestBody;
64 import org.springframework.web.bind.annotation.RequestMapping;
65 import org.springframework.web.bind.annotation.RequestParam;
66 import org.springframework.web.bind.annotation.RestController;
67 import reactor.core.publisher.Mono;
68
69 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
70 @RestController("A1-EI")
71 @Tag(name = A1eConsts.CONSUMER_API_NAME, description = A1eConsts.CONSUMER_API_DESCRIPTION)
72 @RequestMapping(path = A1eConsts.API_ROOT, produces = MediaType.APPLICATION_JSON_VALUE)
73 public class A1eController {
74
75     private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
76
77     @Autowired
78     ApplicationConfig applicationConfig;
79
80     @Autowired
81     private InfoJobs eiJobs;
82
83     @Autowired
84     private InfoTypes eiTypes;
85
86     @Autowired
87     private InfoProducers infoProducers;
88
89     @Autowired
90     ProducerCallbacks producerCallbacks;
91
92     private static Gson gson = new GsonBuilder().create();
93
94     @GetMapping(path = "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
95     @Operation(summary = "EI type identifiers", description = "")
96     @ApiResponses(
97         value = { //
98             @ApiResponse(
99                 responseCode = "200",
100                 description = "EI type identifiers", //
101                 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), //
102         })
103     public ResponseEntity<Object> getEiTypeIdentifiers( //
104     ) {
105         List<String> result = new ArrayList<>();
106         for (InfoType eiType : this.eiTypes.getAllInfoTypes()) {
107             result.add(eiType.getId());
108         }
109
110         return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
111     }
112
113     @GetMapping(path = "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
114     @Operation(summary = "Individual EI type", description = "")
115     @ApiResponses(
116         value = { //
117             @ApiResponse(
118                 responseCode = "200",
119                 description = "EI type", //
120                 content = @Content(schema = @Schema(implementation = A1eEiTypeInfo.class))), //
121             @ApiResponse(
122                 responseCode = "404",
123                 description = "Enrichment Information type is not found", //
124                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
125         })
126     public ResponseEntity<Object> getEiType( //
127         @PathVariable("eiTypeId") String eiTypeId) {
128         try {
129             this.eiTypes.getType(eiTypeId); // Make sure that the type exists
130             A1eEiTypeInfo info = toEiTypeInfo();
131             return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
132         } catch (Exception e) {
133             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
134         }
135     }
136
137     @GetMapping(path = "/eijobs", produces = MediaType.APPLICATION_JSON_VALUE)
138     @Operation(summary = "EI job identifiers", description = "query for EI job identifiers")
139     @ApiResponses(
140         value = { //
141             @ApiResponse(
142                 responseCode = "200",
143                 description = "EI job identifiers", //
144                 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
145             @ApiResponse(
146                 responseCode = "404",
147                 description = "Enrichment Information type is not found", //
148                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
149         })
150     public ResponseEntity<Object> getEiJobIds( //
151         @Parameter(
152             name = A1eConsts.EI_TYPE_ID_PARAM,
153             required = false, //
154             description = A1eConsts.EI_TYPE_ID_PARAM_DESCRIPTION) //
155         @RequestParam(name = A1eConsts.EI_TYPE_ID_PARAM, required = false) String eiTypeId,
156         @Parameter(
157             name = A1eConsts.OWNER_PARAM,
158             required = false, //
159             description = A1eConsts.OWNER_PARAM_DESCRIPTION) //
160         @RequestParam(name = A1eConsts.OWNER_PARAM, required = false) String owner) {
161         try {
162             List<String> result = new ArrayList<>();
163             if (owner != null) {
164                 for (InfoJob job : this.eiJobs.getJobsForOwner(owner)) {
165                     if (eiTypeId == null || job.getTypeId().equals(eiTypeId)) {
166                         result.add(job.getId());
167                     }
168                 }
169             } else if (eiTypeId != null) {
170                 this.eiJobs.getJobsForType(eiTypeId).forEach(job -> result.add(job.getId()));
171             } else {
172                 this.eiJobs.getJobs().forEach(job -> result.add(job.getId()));
173             }
174             return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
175         } catch (
176
177         Exception e) {
178             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
179         }
180     }
181
182     @GetMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE) //
183     @Operation(summary = "Individual EI job", description = "") //
184     @ApiResponses(
185         value = { //
186             @ApiResponse(
187                 responseCode = "200",
188                 description = "EI job", //
189                 content = @Content(schema = @Schema(implementation = A1eEiJobInfo.class))), //
190             @ApiResponse(
191                 responseCode = "404",
192                 description = "Enrichment Information job is not found", //
193                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
194         })
195     public ResponseEntity<Object> getIndividualEiJob( //
196         @PathVariable("eiJobId") String eiJobId) {
197         try {
198             InfoJob job = this.eiJobs.getJob(eiJobId);
199             return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
200         } catch (Exception e) {
201             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
202         }
203     }
204
205     @GetMapping(path = "/eijobs/{eiJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
206     @Operation(summary = "EI job status", description = "")
207     @ApiResponses(
208         value = { //
209             @ApiResponse(
210                 responseCode = "200",
211                 description = "EI job status", //
212                 content = @Content(schema = @Schema(implementation = A1eEiJobStatus.class))), //
213             @ApiResponse(
214                 responseCode = "404",
215                 description = "Enrichment Information job is not found", //
216                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
217         })
218     public ResponseEntity<Object> getEiJobStatus( //
219         @PathVariable("eiJobId") String eiJobId) {
220         try {
221             InfoJob job = this.eiJobs.getJob(eiJobId);
222             return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
223         } catch (Exception e) {
224             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
225         }
226     }
227
228     private A1eEiJobStatus toEiJobStatus(InfoJob job) {
229         return this.infoProducers.isJobEnabled(job) ? new A1eEiJobStatus(A1eEiJobStatus.EiJobStatusValues.ENABLED)
230             : new A1eEiJobStatus(A1eEiJobStatus.EiJobStatusValues.DISABLED);
231
232     }
233
234     @DeleteMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
235     @Operation(summary = "Individual EI job", description = "")
236     @ApiResponses(
237         value = { //
238             @ApiResponse(
239                 responseCode = "200",
240                 description = "Not used", //
241                 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
242             @ApiResponse(
243                 responseCode = "204",
244                 description = "Job deleted", //
245                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
246             @ApiResponse(
247                 responseCode = "404",
248                 description = "Enrichment Information job is not found", //
249                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
250         })
251     public ResponseEntity<Object> deleteIndividualEiJob( //
252         @PathVariable("eiJobId") String eiJobId) {
253         try {
254             InfoJob job = this.eiJobs.getJob(eiJobId);
255             this.eiJobs.remove(job, this.infoProducers);
256             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
257         } catch (Exception e) {
258             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
259         }
260     }
261
262     @PutMapping(
263         path = "/eijobs/{eiJobId}", //
264         produces = MediaType.APPLICATION_JSON_VALUE, //
265         consumes = MediaType.APPLICATION_JSON_VALUE)
266     @Operation(summary = "Individual EI job", description = "")
267     @ApiResponses(
268         value = { //
269             @ApiResponse(
270                 responseCode = "201",
271                 description = "Job created", //
272                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
273             @ApiResponse(
274                 responseCode = "200",
275                 description = "Job updated", //
276                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
277             @ApiResponse(
278                 responseCode = "404",
279                 description = "Enrichment Information type is not found", //
280                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))),
281             @ApiResponse(
282                 responseCode = "400",
283                 description = "Input validation failed", //
284                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
285             @ApiResponse(
286                 responseCode = "409",
287                 description = "Cannot modify job type", //
288                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))
289
290         })
291
292     public Mono<ResponseEntity<Object>> putIndividualEiJob( //
293         @PathVariable("eiJobId") String eiJobId, //
294         @RequestBody A1eEiJobInfo eiJobObject) {
295
296         final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
297
298         return validatePutEiJob(eiJobId, eiJobObject) //
299             .flatMap(this::startEiJob) //
300             .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
301             .map(newEiJob -> new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)) //
302             .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.INTERNAL_SERVER_ERROR)));
303     }
304
305     private Mono<InfoJob> startEiJob(InfoJob newEiJob) {
306         return this.producerCallbacks.startInfoSubscriptionJob(newEiJob, infoProducers) //
307             .doOnNext(noOfAcceptingProducers -> this.logger.debug(
308                 "Started EI job {}, number of activated producers: {}", newEiJob.getId(), noOfAcceptingProducers)) //
309             .map(noOfAcceptingProducers -> newEiJob);
310     }
311
312     private Mono<InfoJob> validatePutEiJob(String eiJobId, A1eEiJobInfo eiJobInfo) {
313         try {
314             InfoType eiType = this.eiTypes.getType(eiJobInfo.eiTypeId);
315             validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobDefinition);
316             InfoJob existingEiJob = this.eiJobs.get(eiJobId);
317             validateUri(eiJobInfo.jobResultUri);
318             validateUri(eiJobInfo.statusNotificationUri);
319
320             if (existingEiJob != null && !existingEiJob.getTypeId().equals(eiJobInfo.eiTypeId)) {
321                 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
322             }
323             return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
324         } catch (Exception e) {
325             return Mono.error(e);
326         }
327     }
328
329     private void validateUri(String url) throws URISyntaxException, ServiceException {
330         if (url != null && !url.isEmpty()) {
331             URI uri = new URI(url);
332             if (!uri.isAbsolute()) {
333                 throw new ServiceException("URI: " + url + " is not absolute", HttpStatus.BAD_REQUEST);
334             }
335         }
336     }
337
338     private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
339         if (schemaObj != null) { // schema is optional for now
340             try {
341                 ObjectMapper mapper = new ObjectMapper();
342
343                 String schemaAsString = mapper.writeValueAsString(schemaObj);
344                 JSONObject schemaJSON = new JSONObject(schemaAsString);
345                 var schema = org.everit.json.schema.loader.SchemaLoader.load(schemaJSON);
346
347                 String objectAsString = mapper.writeValueAsString(object);
348                 JSONObject json = new JSONObject(objectAsString);
349                 schema.validate(json);
350             } catch (Exception e) {
351                 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.BAD_REQUEST);
352             }
353         }
354     }
355
356     private InfoJob toEiJob(A1eEiJobInfo info, String id, InfoType type) {
357         return InfoJob.builder() //
358             .id(id) //
359             .typeId(type.getId()) //
360             .owner(info.owner) //
361             .jobData(info.jobDefinition) //
362             .targetUrl(info.jobResultUri) //
363             .jobStatusUrl(info.statusNotificationUri == null ? "" : info.statusNotificationUri) //
364             .build();
365     }
366
367     private A1eEiTypeInfo toEiTypeInfo() {
368         return new A1eEiTypeInfo();
369     }
370
371     private A1eEiJobInfo toEiJobInfo(InfoJob s) {
372         return new A1eEiJobInfo(s.getTypeId(), s.getJobData(), s.getOwner(), s.getTargetUrl(), s.getJobStatusUrl());
373     }
374 }