Fix Sonar issues
[nonrtric.git] / enrichment-coordinator-service / src / main / java / org / oransc / enrichment / controllers / r1producer / ProducerController.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.r1producer;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25
26 import io.swagger.v3.oas.annotations.Operation;
27 import io.swagger.v3.oas.annotations.Parameter;
28 import io.swagger.v3.oas.annotations.media.ArraySchema;
29 import io.swagger.v3.oas.annotations.media.Content;
30 import io.swagger.v3.oas.annotations.media.Schema;
31 import io.swagger.v3.oas.annotations.responses.ApiResponse;
32 import io.swagger.v3.oas.annotations.responses.ApiResponses;
33 import io.swagger.v3.oas.annotations.tags.Tag;
34
35 import java.net.URI;
36 import java.net.URISyntaxException;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.List;
40
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.InfoJob;
45 import org.oransc.enrichment.repository.InfoJobs;
46 import org.oransc.enrichment.repository.InfoProducer;
47 import org.oransc.enrichment.repository.InfoProducers;
48 import org.oransc.enrichment.repository.InfoType;
49 import org.oransc.enrichment.repository.InfoTypes;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.http.HttpStatus;
52 import org.springframework.http.MediaType;
53 import org.springframework.http.ResponseEntity;
54 import org.springframework.web.bind.annotation.DeleteMapping;
55 import org.springframework.web.bind.annotation.GetMapping;
56 import org.springframework.web.bind.annotation.PathVariable;
57 import org.springframework.web.bind.annotation.PutMapping;
58 import org.springframework.web.bind.annotation.RequestBody;
59 import org.springframework.web.bind.annotation.RequestParam;
60 import org.springframework.web.bind.annotation.RestController;
61
62 @SuppressWarnings("squid:S2629") // Invoke method(s) only conditionally
63 @RestController("Producer registry")
64 @Tag(name = ProducerConsts.PRODUCER_API_NAME)
65 public class ProducerController {
66
67     private static Gson gson = new GsonBuilder().create();
68
69     @Autowired
70     private InfoJobs infoJobs;
71
72     @Autowired
73     private InfoTypes infoTypes;
74
75     @Autowired
76     private InfoProducers infoProducers;
77
78     @GetMapping(path = ProducerConsts.API_ROOT + "/info-types", produces = MediaType.APPLICATION_JSON_VALUE) //
79     @Operation(summary = "Info Type identifiers", description = "") //
80     @ApiResponses(
81         value = { //
82             @ApiResponse(
83                 responseCode = "200",
84                 description = "Info Type identifiers", //
85                 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))) //
86         })
87     public ResponseEntity<Object> getInfoTypdentifiers( //
88     ) {
89         List<String> result = new ArrayList<>();
90         for (InfoType infoType : this.infoTypes.getAllInfoTypes()) {
91             result.add(infoType.getId());
92         }
93
94         return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
95     }
96
97     @GetMapping(
98         path = ProducerConsts.API_ROOT + "/info-types/{infoTypeId}",
99         produces = MediaType.APPLICATION_JSON_VALUE)
100     @Operation(summary = "Individual Information Type", description = "")
101     @ApiResponses(
102         value = { //
103             @ApiResponse(
104                 responseCode = "200",
105                 description = "Info Type", //
106                 content = @Content(schema = @Schema(implementation = ProducerInfoTypeInfo.class))), //
107             @ApiResponse(
108                 responseCode = "404",
109                 description = "Information type is not found", //
110                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))})
111     public ResponseEntity<Object> getInfoType( //
112         @PathVariable("infoTypeId") String infoTypeId) {
113         try {
114             InfoType t = this.infoTypes.getType(infoTypeId);
115             ProducerInfoTypeInfo info = toInfoTypeInfo(t);
116             return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
117         } catch (Exception e) {
118             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
119         }
120     }
121
122     @PutMapping(
123         path = ProducerConsts.API_ROOT + "/info-types/{infoTypeId}",
124         produces = MediaType.APPLICATION_JSON_VALUE)
125     @ApiResponses(
126         value = { //
127             @ApiResponse(
128                 responseCode = "200",
129                 description = "Type updated", //
130                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
131             @ApiResponse(
132                 responseCode = "201",
133                 description = "Type created", //
134                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
135             @ApiResponse(
136                 responseCode = "400",
137                 description = "Bad request", //
138                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))})
139     @Operation(summary = "Individual Information Type", description = "")
140     public ResponseEntity<Object> putInfoType( //
141         @PathVariable("infoTypeId") String infoTypeId, //
142         @RequestBody ProducerInfoTypeInfo registrationInfo) {
143
144         InfoType previousDefinition = this.infoTypes.get(infoTypeId);
145         if (registrationInfo.jobDataSchema == null) {
146             return ErrorResponse.create("No schema provided", HttpStatus.BAD_REQUEST);
147         }
148         this.infoTypes.put(new InfoType(infoTypeId, registrationInfo.jobDataSchema));
149         return new ResponseEntity<>(previousDefinition == null ? HttpStatus.CREATED : HttpStatus.OK);
150     }
151
152     @DeleteMapping(
153         path = ProducerConsts.API_ROOT + "/info-types/{infoTypeId}",
154         produces = MediaType.APPLICATION_JSON_VALUE) //
155     @Operation(summary = "Individual Information Type", description = "") //
156     @ApiResponses(
157         value = { //
158             @ApiResponse(
159                 responseCode = "200",
160                 description = "Not used", //
161                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
162             @ApiResponse(
163                 responseCode = "204",
164                 description = "Producer deleted", //
165                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
166             @ApiResponse(
167                 responseCode = "404",
168                 description = "Information type is not found", //
169                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
170             @ApiResponse(
171                 responseCode = "406",
172                 description = "The Information type has one or several active producers", //
173                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
174         })
175     public ResponseEntity<Object> deleteInfoType( //
176         @PathVariable("infoTypeId") String infoTypeId) {
177
178         InfoType type = this.infoTypes.get(infoTypeId);
179         if (type == null) {
180             return ErrorResponse.create("Information type not found", HttpStatus.NOT_FOUND);
181         }
182         if (!this.infoProducers.getProducersForType(type).isEmpty()) {
183             String firstProducerId = this.infoProducers.getProducersForType(type).iterator().next().getId();
184             return ErrorResponse.create("The type has active producers: " + firstProducerId, HttpStatus.NOT_ACCEPTABLE);
185         }
186         this.infoTypes.remove(type);
187         return new ResponseEntity<>(HttpStatus.NO_CONTENT);
188     }
189
190     @GetMapping(path = ProducerConsts.API_ROOT + "/info-producers", produces = MediaType.APPLICATION_JSON_VALUE)
191     @Operation(summary = "Information producer identifiers", description = "")
192     @ApiResponses(
193         value = { //
194             @ApiResponse(
195                 responseCode = "200",
196                 description = "Information producer identifiers", //
197                 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))) //
198         })
199     public ResponseEntity<Object> getInfoProducerIdentifiers( //
200         @Parameter(
201             name = "info_type_id",
202             required = false,
203             description = "If given, only the producers for the EI Data type is returned.") //
204         @RequestParam(name = "info_type_id", required = false) String typeId //
205     ) {
206         List<String> result = new ArrayList<>();
207         for (InfoProducer infoProducer : typeId == null ? this.infoProducers.getAllProducers()
208             : this.infoProducers.getProducersForType(typeId)) {
209             result.add(infoProducer.getId());
210         }
211
212         return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
213     }
214
215     @GetMapping(
216         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}",
217         produces = MediaType.APPLICATION_JSON_VALUE)
218     @Operation(summary = "Individual Information Producer", description = "")
219     @ApiResponses(
220         value = { //
221             @ApiResponse(
222                 responseCode = "200",
223                 description = "Information producer", //
224                 content = @Content(schema = @Schema(implementation = ProducerRegistrationInfo.class))), //
225             @ApiResponse(
226                 responseCode = "404",
227                 description = "Information producer is not found", //
228                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
229         })
230     public ResponseEntity<Object> getInfoProducer( //
231         @PathVariable("infoProducerId") String infoProducerId) {
232         try {
233             InfoProducer  producer = this.infoProducers.getProducer(infoProducerId);
234             ProducerRegistrationInfo info = toProducerRegistrationInfo(producer);
235             return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
236         } catch (Exception e) {
237             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
238         }
239     }
240
241     @GetMapping(
242         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}/info-jobs",
243         produces = MediaType.APPLICATION_JSON_VALUE)
244     @Operation(
245         summary = "Information Job definitions",
246         description = "Information Job definitions for one Information Producer")
247     @ApiResponses(
248         value = { //
249             @ApiResponse(
250                 responseCode = "404",
251                 description = "Information producer is not found", //
252                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
253             @ApiResponse(
254                 responseCode = "200",
255                 description = "Information producer", //
256                 content = @Content(array = @ArraySchema(schema = @Schema(implementation = ProducerJobInfo.class)))), //
257         })
258     public ResponseEntity<Object> getInfoProducerJobs( //
259         @PathVariable("infoProducerId") String infoProducerId) {
260         try {
261             InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
262             Collection<ProducerJobInfo> producerJobs = new ArrayList<>();
263             for (InfoType type : producer.getInfoTypes()) {
264                 for (InfoJob infoJob : this.infoJobs.getJobsForType(type)) {
265                     ProducerJobInfo request = new ProducerJobInfo(infoJob);
266                     producerJobs.add(request);
267                 }
268             }
269
270             return new ResponseEntity<>(gson.toJson(producerJobs), HttpStatus.OK);
271         } catch (Exception e) {
272             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
273         }
274     }
275
276     @GetMapping(
277         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}/status",
278         produces = MediaType.APPLICATION_JSON_VALUE) //
279     @Operation(summary = "Information producer status") //
280     @ApiResponses(
281         value = { //
282             @ApiResponse(
283                 responseCode = "200",
284                 description = "Information producer status", //
285                 content = @Content(schema = @Schema(implementation = ProducerStatusInfo.class))), //
286             @ApiResponse(
287                 responseCode = "404",
288                 description = "Information producer is not found", //
289                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
290         })
291     public ResponseEntity<Object> getInfoProducerStatus( //
292         @PathVariable("infoProducerId") String infoProducerId) {
293         try {
294             InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
295             return new ResponseEntity<>(gson.toJson(producerStatusInfo(producer)), HttpStatus.OK);
296         } catch (Exception e) {
297             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
298         }
299     }
300
301     private ProducerStatusInfo producerStatusInfo(InfoProducer producer) {
302         var opState = producer.isAvailable() ? ProducerStatusInfo.OperationalState.ENABLED
303             : ProducerStatusInfo.OperationalState.DISABLED;
304         return new ProducerStatusInfo(opState);
305     }
306
307     @PutMapping(
308         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}", //
309         produces = MediaType.APPLICATION_JSON_VALUE)
310     @Operation(summary = "Individual Information Producer", description = "")
311     @ApiResponses(
312         value = { //
313             @ApiResponse(
314                 responseCode = "201",
315                 description = "Producer created", //
316                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
317             @ApiResponse(
318                 responseCode = "200",
319                 description = "Producer updated", //
320                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
321             @ApiResponse(
322                 responseCode = "404",
323                 description = "Producer not found", //
324                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
325         })
326     public ResponseEntity<Object> putInfoProducer( //
327         @PathVariable("infoProducerId") String infoProducerId, //
328         @RequestBody ProducerRegistrationInfo registrationInfo) {
329         try {
330             validateUri(registrationInfo.jobCallbackUrl);
331             validateUri(registrationInfo.producerSupervisionCallbackUrl);
332             InfoProducer previousDefinition = this.infoProducers.get(infoProducerId);
333             this.infoProducers.registerProducer(toProducerRegistrationInfo(infoProducerId, registrationInfo));
334             return new ResponseEntity<>(previousDefinition == null ? HttpStatus.CREATED : HttpStatus.OK);
335         } catch (Exception e) {
336             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
337         }
338     }
339
340     private void validateUri(String url) throws URISyntaxException, ServiceException {
341         if (url != null && !url.isEmpty()) {
342             URI uri = new URI(url);
343             if (!uri.isAbsolute()) {
344                 throw new ServiceException("URI: " + url + " is not absolute", HttpStatus.CONFLICT);
345             }
346         } else {
347             throw new ServiceException("Missing required URL", HttpStatus.CONFLICT);
348         }
349     }
350
351     @DeleteMapping(
352         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}",
353         produces = MediaType.APPLICATION_JSON_VALUE)
354     @Operation(summary = "Individual Information Producer", description = "")
355     @ApiResponses(
356         value = { //
357             @ApiResponse(
358                 responseCode = "200",
359                 description = "Not used", //
360                 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
361             @ApiResponse(
362                 responseCode = "204",
363                 description = "Producer deleted", //
364                 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
365             @ApiResponse(
366                 responseCode = "404",
367                 description = "Producer is not found", //
368                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
369         })
370     public ResponseEntity<Object> deleteInfoProducer(@PathVariable("infoProducerId") String infoProducerId) {
371         try {
372             final InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
373             this.infoProducers.deregisterProducer(producer);
374             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
375         } catch (Exception e) {
376             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
377         }
378     }
379
380     private ProducerRegistrationInfo toProducerRegistrationInfo(InfoProducer p) {
381         Collection<String> types = new ArrayList<>();
382         for (InfoType type : p.getInfoTypes()) {
383             types.add(type.getId());
384         }
385         return new ProducerRegistrationInfo(types, p.getJobCallbackUrl(), p.getProducerSupervisionCallbackUrl());
386     }
387
388     private ProducerInfoTypeInfo toInfoTypeInfo(InfoType t) {
389         return new ProducerInfoTypeInfo(t.getJobDataSchema());
390     }
391
392     private InfoProducers.InfoProducerRegistrationInfo toProducerRegistrationInfo(String infoProducerId,
393         ProducerRegistrationInfo info) throws ServiceException {
394         Collection<InfoType> supportedTypes = new ArrayList<>();
395         for (String typeId : info.supportedTypeIds) {
396             InfoType type = this.infoTypes.getType(typeId);
397             supportedTypes.add(type);
398         }
399
400         return InfoProducers.InfoProducerRegistrationInfo.builder() //
401             .id(infoProducerId) //
402             .jobCallbackUrl(info.jobCallbackUrl) //
403             .producerSupervisionCallbackUrl(info.producerSupervisionCallbackUrl) //
404             .supportedTypes(supportedTypes) //
405             .build();
406     }
407 }