2 * ========================LICENSE_START=================================
5 * Copyright (C) 2020 Nordix Foundation
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.oransc.enrichment.controllers.r1consumer;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
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;
36 import java.lang.invoke.MethodHandles;
38 import java.net.URISyntaxException;
39 import java.util.ArrayList;
40 import java.util.Collection;
41 import java.util.List;
43 import org.json.JSONObject;
44 import org.oransc.enrichment.controllers.ErrorResponse;
45 import org.oransc.enrichment.controllers.VoidResponse;
46 import org.oransc.enrichment.controllers.r1producer.ProducerCallbacks;
47 import org.oransc.enrichment.exceptions.ServiceException;
48 import org.oransc.enrichment.repository.InfoJob;
49 import org.oransc.enrichment.repository.InfoJobs;
50 import org.oransc.enrichment.repository.InfoProducer;
51 import org.oransc.enrichment.repository.InfoProducers;
52 import org.oransc.enrichment.repository.InfoType;
53 import org.oransc.enrichment.repository.InfoTypeSubscriptions;
54 import org.oransc.enrichment.repository.InfoTypes;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.springframework.beans.factory.annotation.Autowired;
58 import org.springframework.http.HttpStatus;
59 import org.springframework.http.MediaType;
60 import org.springframework.http.ResponseEntity;
61 import org.springframework.web.bind.annotation.DeleteMapping;
62 import org.springframework.web.bind.annotation.GetMapping;
63 import org.springframework.web.bind.annotation.PathVariable;
64 import org.springframework.web.bind.annotation.PutMapping;
65 import org.springframework.web.bind.annotation.RequestBody;
66 import org.springframework.web.bind.annotation.RequestMapping;
67 import org.springframework.web.bind.annotation.RequestParam;
68 import org.springframework.web.bind.annotation.RestController;
69 import reactor.core.publisher.Mono;
71 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
72 @RestController("Consumer API")
73 @Tag(name = ConsumerConsts.CONSUMER_API_NAME)
74 @RequestMapping(path = ConsumerConsts.API_ROOT, produces = MediaType.APPLICATION_JSON_VALUE)
75 public class ConsumerController {
77 private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
78 private final InfoJobs infoJobs;
79 private final InfoTypes infoTypes;
80 private final InfoProducers infoProducers;
81 private final ProducerCallbacks producerCallbacks;
82 private final InfoTypeSubscriptions infoTypeSubscriptions;
83 private static Gson gson = new GsonBuilder().create();
85 public ConsumerController(@Autowired InfoJobs jobs, @Autowired InfoTypes infoTypes,
86 @Autowired InfoProducers infoProducers, @Autowired ProducerCallbacks producerCallbacks,
87 @Autowired InfoTypeSubscriptions infoTypeSubscriptions) {
88 this.infoProducers = infoProducers;
90 this.infoTypeSubscriptions = infoTypeSubscriptions;
91 this.infoTypes = infoTypes;
92 this.producerCallbacks = producerCallbacks;
95 @GetMapping(path = "/info-types", produces = MediaType.APPLICATION_JSON_VALUE)
96 @Operation(summary = "Information type identifiers", description = "")
100 responseCode = "200",
101 description = "Information type identifiers", //
102 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), //
104 public ResponseEntity<Object> getinfoTypeIdentifiers( //
106 List<String> result = new ArrayList<>();
107 for (InfoType infoType : this.infoTypes.getAllInfoTypes()) {
108 result.add(infoType.getId());
111 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
114 @GetMapping(path = "/info-types/{infoTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
115 @Operation(summary = "Individual information type", description = "")
119 responseCode = "200",
120 description = "Information type", //
121 content = @Content(schema = @Schema(implementation = ConsumerInfoTypeInfo.class))), //
123 responseCode = "404",
124 description = "Information type is not found", //
125 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
127 public ResponseEntity<Object> getInfoType( //
128 @PathVariable("infoTypeId") String infoTypeId) {
130 InfoType type = this.infoTypes.getType(infoTypeId);
131 ConsumerInfoTypeInfo info = toInfoTypeInfo(type);
132 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
133 } catch (Exception e) {
134 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
138 @GetMapping(path = "/info-jobs", produces = MediaType.APPLICATION_JSON_VALUE)
139 @Operation(summary = "Information Job identifiers", description = "query for information job identifiers")
143 responseCode = "200",
144 description = "Information information job identifiers", //
145 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
147 responseCode = "404",
148 description = "Information type is not found", //
149 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
151 public ResponseEntity<Object> getJobIds( //
153 name = ConsumerConsts.INFO_TYPE_ID_PARAM,
155 description = ConsumerConsts.INFO_TYPE_ID_PARAM_DESCRIPTION) //
156 @RequestParam(name = ConsumerConsts.INFO_TYPE_ID_PARAM, required = false) String infoTypeId,
158 name = ConsumerConsts.OWNER_PARAM,
160 description = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
161 @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
163 List<String> result = new ArrayList<>();
165 for (InfoJob job : this.infoJobs.getJobsForOwner(owner)) {
166 if (infoTypeId == null || job.getTypeId().equals(infoTypeId)) {
167 result.add(job.getId());
170 } else if (infoTypeId != null) {
171 this.infoJobs.getJobsForType(infoTypeId).forEach(job -> result.add(job.getId()));
173 this.infoJobs.getJobs().forEach(job -> result.add(job.getId()));
175 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
179 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
183 @GetMapping(path = "/info-jobs/{infoJobId}", produces = MediaType.APPLICATION_JSON_VALUE) //
184 @Operation(summary = ConsumerConsts.INDIVIDUAL_JOB, description = "") //
188 responseCode = "200",
189 description = "Information subscription job", //
190 content = @Content(schema = @Schema(implementation = ConsumerJobInfo.class))), //
192 responseCode = "404",
193 description = "Information subscription job is not found", //
194 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
196 public ResponseEntity<Object> getIndividualEiJob( //
197 @PathVariable("infoJobId") String infoJobId) {
199 InfoJob job = this.infoJobs.getJob(infoJobId);
200 return new ResponseEntity<>(gson.toJson(toInfoJobInfo(job)), HttpStatus.OK);
201 } catch (Exception e) {
202 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
206 @GetMapping(path = "/info-jobs/{infoJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
207 @Operation(summary = "Job status", description = "")
211 responseCode = "200",
212 description = "Information subscription job status", //
213 content = @Content(schema = @Schema(implementation = ConsumerJobStatus.class))), //
215 responseCode = "404",
216 description = "Information subscription job is not found", //
217 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
219 public ResponseEntity<Object> getEiJobStatus( //
220 @PathVariable("infoJobId") String jobId) {
222 InfoJob job = this.infoJobs.getJob(jobId);
223 return new ResponseEntity<>(gson.toJson(toInfoJobStatus(job)), HttpStatus.OK);
224 } catch (Exception e) {
225 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
229 private ConsumerJobStatus toInfoJobStatus(InfoJob job) {
230 Collection<String> producerIds = new ArrayList<>();
231 this.infoProducers.getProducersForType(job.getTypeId()).forEach(producer -> producerIds.add(producer.getId()));
232 return this.infoProducers.isJobEnabled(job)
233 ? new ConsumerJobStatus(ConsumerJobStatus.InfoJobStatusValues.ENABLED, producerIds)
234 : new ConsumerJobStatus(ConsumerJobStatus.InfoJobStatusValues.DISABLED, producerIds);
238 @DeleteMapping(path = "/info-jobs/{infoJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
239 @Operation(summary = ConsumerConsts.INDIVIDUAL_JOB, description = "")
243 responseCode = "200",
244 description = "Not used", //
245 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
247 responseCode = "204",
248 description = "Job deleted", //
249 content = @Content(schema = @Schema(implementation = VoidResponse.class))), // "Individual
252 responseCode = "404",
253 description = "Information subscription job is not found", //
254 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
256 public ResponseEntity<Object> deleteIndividualEiJob( //
257 @PathVariable("infoJobId") String jobId) {
259 InfoJob job = this.infoJobs.getJob(jobId);
260 this.infoJobs.remove(job, this.infoProducers);
261 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
262 } catch (Exception e) {
263 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
268 path = "/info-jobs/{infoJobId}", //
269 produces = MediaType.APPLICATION_JSON_VALUE, //
270 consumes = MediaType.APPLICATION_JSON_VALUE)
271 @Operation(summary = ConsumerConsts.INDIVIDUAL_JOB, description = ConsumerConsts.PUT_INDIVIDUAL_JOB_DESCRIPTION)
275 responseCode = "201",
276 description = "Job created", //
277 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
279 responseCode = "200",
280 description = "Job updated", //
281 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
283 responseCode = "404",
284 description = "Information type is not found", //
285 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
287 public Mono<ResponseEntity<Object>> putIndividualInfoJob( //
288 @PathVariable("infoJobId") String jobId, //
290 name = ConsumerConsts.PERFORM_TYPE_CHECK_PARAM,
292 description = ConsumerConsts.PERFORM_TYPE_CHECK_PARAM_DESCRIPTION) //
294 name = ConsumerConsts.PERFORM_TYPE_CHECK_PARAM,
296 defaultValue = "false") boolean performTypeCheck,
297 @RequestBody ConsumerJobInfo informationJobObject) {
299 final boolean isNewJob = this.infoJobs.get(jobId) == null;
301 return validatePutInfoJob(jobId, informationJobObject, performTypeCheck) //
302 .flatMap(this::startInfoSubscriptionJob) //
303 .doOnNext(this.infoJobs::put) //
304 .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
305 .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
308 @GetMapping(path = "/info-type-subscription", produces = MediaType.APPLICATION_JSON_VALUE)
310 summary = "Information type subscription identifiers",
311 description = "query for information type subscription identifiers")
315 responseCode = "200",
316 description = "Information type subscription identifiers", //
317 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),})
318 public ResponseEntity<Object> getInfoTypeSubscriptions( //
321 name = ConsumerConsts.OWNER_PARAM,
323 description = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
324 @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
326 List<String> result = new ArrayList<>();
328 this.infoTypeSubscriptions.getSubscriptionsForOwner(owner)
329 .forEach(subscription -> result.add(subscription.getId()));
331 this.infoTypeSubscriptions.getAllSubscriptions()
332 .forEach(subscription -> result.add(subscription.getId()));
334 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
335 } catch (Exception e) {
336 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
340 @GetMapping(path = "/info-type-subscription/{subscriptionId}", produces = MediaType.APPLICATION_JSON_VALUE) //
341 @Operation(summary = ConsumerConsts.INDIVIDUAL_TYPE_SUBSCRIPTION, description = "") //
345 responseCode = "200",
346 description = "Type subscription", //
347 content = @Content(schema = @Schema(implementation = ConsumerTypeSubscriptionInfo.class))), //
349 responseCode = "404",
350 description = "Subscription is not found", //
351 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
353 public ResponseEntity<Object> getIndividualTypeSubscription( //
354 @PathVariable("subscriptionId") String subscriptionId) {
356 InfoTypeSubscriptions.SubscriptionInfo subscription =
357 this.infoTypeSubscriptions.getSubscription(subscriptionId);
358 return new ResponseEntity<>(gson.toJson(toTypeSuscriptionInfo(subscription)), HttpStatus.OK);
359 } catch (Exception e) {
360 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
365 path = "/info-type-subscription/{subscriptionId}", //
366 produces = MediaType.APPLICATION_JSON_VALUE, //
367 consumes = MediaType.APPLICATION_JSON_VALUE)
369 summary = ConsumerConsts.INDIVIDUAL_TYPE_SUBSCRIPTION,
370 description = ConsumerConsts.TYPE_SUBSCRIPTION_DESCRIPTION)
374 responseCode = "201",
375 description = "Subscription created", //
376 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
378 responseCode = "200",
379 description = "Subscription updated", //
380 content = @Content(schema = @Schema(implementation = VoidResponse.class))) //
382 public Mono<ResponseEntity<Object>> putIndividualTypeSubscription( //
383 @PathVariable("subscriptionId") String subscriptionId, //
384 @RequestBody ConsumerTypeSubscriptionInfo subscription) {
386 final boolean isNewSubscription = this.infoTypeSubscriptions.get(subscriptionId) == null;
387 this.infoTypeSubscriptions.put(toTypeSuscriptionInfo(subscription, subscriptionId));
388 return Mono.just(new ResponseEntity<>(isNewSubscription ? HttpStatus.CREATED : HttpStatus.OK));
391 @DeleteMapping(path = "/info-type-subscription/{subscriptionId}", produces = MediaType.APPLICATION_JSON_VALUE)
392 @Operation(summary = ConsumerConsts.INDIVIDUAL_TYPE_SUBSCRIPTION, description = "")
396 responseCode = "200",
397 description = "Not used", //
398 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
400 responseCode = "204",
401 description = "Subscription deleted", //
402 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
404 responseCode = "404",
405 description = "Subscription is not found", //
406 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
408 public ResponseEntity<Object> deleteIndividualTypeSubscription( //
409 @PathVariable("subscriptionId") String subscriptionId) {
411 InfoTypeSubscriptions.SubscriptionInfo subscription =
412 this.infoTypeSubscriptions.getSubscription(subscriptionId);
413 this.infoTypeSubscriptions.remove(subscription);
414 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
415 } catch (Exception e) {
416 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
420 private ConsumerTypeSubscriptionInfo toTypeSuscriptionInfo(InfoTypeSubscriptions.SubscriptionInfo s) {
421 return new ConsumerTypeSubscriptionInfo(s.getCallbackUrl(), s.getOwner());
424 private InfoTypeSubscriptions.SubscriptionInfo toTypeSuscriptionInfo(ConsumerTypeSubscriptionInfo s,
425 String subscriptionId) {
426 return InfoTypeSubscriptions.SubscriptionInfo.builder() //
427 .apiVersion(ConsumerCallbacks.API_VERSION) //
429 .id(subscriptionId) //
430 .callbackUrl(s.statusResultUri).build();
433 private Mono<InfoJob> startInfoSubscriptionJob(InfoJob newInfoJob) {
434 return this.producerCallbacks.startInfoSubscriptionJob(newInfoJob, infoProducers) //
435 .doOnNext(noOfAcceptingProducers -> this.logger.debug("Started job {}, number of activated producers: {}",
436 newInfoJob.getId(), noOfAcceptingProducers)) //
437 .flatMap(noOfAcceptingProducers -> Mono.just(newInfoJob));
440 private Mono<InfoJob> validatePutInfoJob(String jobId, ConsumerJobInfo jobInfo, boolean performTypeCheck) {
442 if (performTypeCheck) {
443 InfoType infoType = this.infoTypes.getType(jobInfo.infoTypeId);
444 validateJsonObjectAgainstSchema(infoType.getJobDataSchema(), jobInfo.jobDefinition);
446 InfoJob existingEiJob = this.infoJobs.get(jobId);
447 validateUri(jobInfo.statusNotificationUri);
448 validateUri(jobInfo.jobResultUri);
450 if (existingEiJob != null && !existingEiJob.getTypeId().equals(jobInfo.infoTypeId)) {
451 throw new ServiceException("Not allowed to change type for existing job", HttpStatus.CONFLICT);
453 return Mono.just(toEiJob(jobInfo, jobId, jobInfo.infoTypeId));
454 } catch (Exception e) {
455 return Mono.error(e);
459 private void validateUri(String url) throws URISyntaxException, ServiceException {
460 if (url != null && !url.isEmpty()) {
461 URI uri = new URI(url);
462 if (!uri.isAbsolute()) {
463 throw new ServiceException("URI: " + url + " is not absolute", HttpStatus.CONFLICT);
468 private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
469 if (schemaObj != null) { // schema is optional for now
471 ObjectMapper mapper = new ObjectMapper();
473 String schemaAsString = mapper.writeValueAsString(schemaObj);
474 JSONObject schemaJSON = new JSONObject(schemaAsString);
475 var schema = org.everit.json.schema.loader.SchemaLoader.load(schemaJSON);
477 String objectAsString = mapper.writeValueAsString(object);
478 JSONObject json = new JSONObject(objectAsString);
479 schema.validate(json);
480 } catch (Exception e) {
481 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
486 private InfoJob toEiJob(ConsumerJobInfo info, String id, String typeId) {
487 return InfoJob.builder() //
490 .owner(info.owner) //
491 .jobData(info.jobDefinition) //
492 .targetUrl(info.jobResultUri) //
493 .jobStatusUrl(info.statusNotificationUri == null ? "" : info.statusNotificationUri) //
497 private ConsumerInfoTypeInfo toInfoTypeInfo(InfoType type) {
498 return new ConsumerInfoTypeInfo(type.getJobDataSchema(), typeStatus(type),
499 this.infoProducers.getProducerIdsForType(type.getId()).size());
502 private ConsumerInfoTypeInfo.ConsumerTypeStatusValues typeStatus(InfoType type) {
503 for (InfoProducer producer : this.infoProducers.getProducersForType(type)) {
504 if (producer.isAvailable()) {
505 return ConsumerInfoTypeInfo.ConsumerTypeStatusValues.ENABLED;
508 return ConsumerInfoTypeInfo.ConsumerTypeStatusValues.DISABLED;
511 private ConsumerJobInfo toInfoJobInfo(InfoJob s) {
512 return new ConsumerJobInfo(s.getTypeId(), s.getJobData(), s.getOwner(), s.getTargetUrl(), s.getJobStatusUrl());