NONRTRIC - ECS updates of the NBI
[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 p = this.infoProducers.getProducer(infoProducerId);
234             ProducerRegistrationInfo info = toProducerRegistrationInfo(p);
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         ProducerStatusInfo.OperationalState opState =
303             producer.isAvailable() ? ProducerStatusInfo.OperationalState.ENABLED
304                 : ProducerStatusInfo.OperationalState.DISABLED;
305         return new ProducerStatusInfo(opState);
306     }
307
308     @PutMapping(
309         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}", //
310         produces = MediaType.APPLICATION_JSON_VALUE)
311     @Operation(summary = "Individual Information Producer", description = "")
312     @ApiResponses(
313         value = { //
314             @ApiResponse(
315                 responseCode = "201",
316                 description = "Producer created", //
317                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
318             @ApiResponse(
319                 responseCode = "200",
320                 description = "Producer updated", //
321                 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
322             @ApiResponse(
323                 responseCode = "404",
324                 description = "Producer not found", //
325                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
326         })
327     public ResponseEntity<Object> putInfoProducer( //
328         @PathVariable("infoProducerId") String infoProducerId, //
329         @RequestBody ProducerRegistrationInfo registrationInfo) {
330         try {
331             validateUri(registrationInfo.jobCallbackUrl);
332             validateUri(registrationInfo.producerSupervisionCallbackUrl);
333             InfoProducer previousDefinition = this.infoProducers.get(infoProducerId);
334             this.infoProducers.registerProducer(toProducerRegistrationInfo(infoProducerId, registrationInfo));
335             return new ResponseEntity<>(previousDefinition == null ? HttpStatus.CREATED : HttpStatus.OK);
336         } catch (Exception e) {
337             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
338         }
339     }
340
341     private void validateUri(String url) throws URISyntaxException, ServiceException {
342         if (url != null && !url.isEmpty()) {
343             URI uri = new URI(url);
344             if (!uri.isAbsolute()) {
345                 throw new ServiceException("URI: " + url + " is not absolute", HttpStatus.CONFLICT);
346             }
347         } else {
348             throw new ServiceException("Missing required URL", HttpStatus.CONFLICT);
349         }
350     }
351
352     @DeleteMapping(
353         path = ProducerConsts.API_ROOT + "/info-producers/{infoProducerId}",
354         produces = MediaType.APPLICATION_JSON_VALUE)
355     @Operation(summary = "Individual Information Producer", description = "")
356     @ApiResponses(
357         value = { //
358             @ApiResponse(
359                 responseCode = "200",
360                 description = "Not used", //
361                 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
362             @ApiResponse(
363                 responseCode = "204",
364                 description = "Producer deleted", //
365                 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
366             @ApiResponse(
367                 responseCode = "404",
368                 description = "Producer is not found", //
369                 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
370         })
371     public ResponseEntity<Object> deleteInfoProducer(@PathVariable("infoProducerId") String infoProducerId) {
372         try {
373             final InfoProducer producer = this.infoProducers.getProducer(infoProducerId);
374             this.infoProducers.deregisterProducer(producer);
375             return new ResponseEntity<>(HttpStatus.NO_CONTENT);
376         } catch (Exception e) {
377             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
378         }
379     }
380
381     private ProducerRegistrationInfo toProducerRegistrationInfo(InfoProducer p) {
382         Collection<String> types = new ArrayList<>();
383         for (InfoType type : p.getInfoTypes()) {
384             types.add(type.getId());
385         }
386         return new ProducerRegistrationInfo(types, p.getJobCallbackUrl(), p.getProducerSupervisionCallbackUrl());
387     }
388
389     private ProducerInfoTypeInfo toInfoTypeInfo(InfoType t) {
390         return new ProducerInfoTypeInfo(t.getJobDataSchema());
391     }
392
393     private InfoProducers.InfoProducerRegistrationInfo toProducerRegistrationInfo(String infoProducerId,
394         ProducerRegistrationInfo info) throws ServiceException {
395         Collection<InfoType> supportedTypes = new ArrayList<>();
396         for (String typeId : info.supportedTypeIds) {
397             InfoType type = this.infoTypes.getType(typeId);
398             supportedTypes.add(type);
399         }
400
401         return InfoProducers.InfoProducerRegistrationInfo.builder() //
402             .id(infoProducerId) //
403             .jobCallbackUrl(info.jobCallbackUrl) //
404             .producerSupervisionCallbackUrl(info.producerSupervisionCallbackUrl) //
405             .supportedTypes(supportedTypes) //
406             .build();
407     }
408
409 }