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.configuration.ApplicationConfig;
45 import org.oransc.enrichment.controllers.ErrorResponse;
46 import org.oransc.enrichment.controllers.VoidResponse;
47 import org.oransc.enrichment.controllers.r1producer.ProducerCallbacks;
48 import org.oransc.enrichment.exceptions.ServiceException;
49 import org.oransc.enrichment.repository.InfoJob;
50 import org.oransc.enrichment.repository.InfoJobs;
51 import org.oransc.enrichment.repository.InfoProducer;
52 import org.oransc.enrichment.repository.InfoProducers;
53 import org.oransc.enrichment.repository.InfoType;
54 import org.oransc.enrichment.repository.InfoTypeSubscriptions;
55 import org.oransc.enrichment.repository.InfoTypes;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.http.HttpStatus;
60 import org.springframework.http.MediaType;
61 import org.springframework.http.ResponseEntity;
62 import org.springframework.web.bind.annotation.DeleteMapping;
63 import org.springframework.web.bind.annotation.GetMapping;
64 import org.springframework.web.bind.annotation.PathVariable;
65 import org.springframework.web.bind.annotation.PutMapping;
66 import org.springframework.web.bind.annotation.RequestBody;
67 import org.springframework.web.bind.annotation.RequestMapping;
68 import org.springframework.web.bind.annotation.RequestParam;
69 import org.springframework.web.bind.annotation.RestController;
70 import reactor.core.publisher.Mono;
72 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
73 @RestController("Consumer registry")
74 @Tag(name = ConsumerConsts.CONSUMER_API_NAME)
75 @RequestMapping(path = ConsumerConsts.API_ROOT, produces = MediaType.APPLICATION_JSON_VALUE)
76 public class ConsumerController {
78 private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
81 ApplicationConfig applicationConfig;
84 private InfoJobs jobs;
87 private InfoTypes infoTypes;
90 private InfoProducers infoProducers;
93 private ConsumerCallbacks consumerCallbacks;
96 private ProducerCallbacks producerCallbacks;
99 private InfoTypeSubscriptions infoTypeSubscriptions;
101 private static Gson gson = new GsonBuilder().create();
103 @GetMapping(path = "/info-types", produces = MediaType.APPLICATION_JSON_VALUE)
104 @Operation(summary = "Information type identifiers", description = "")
108 responseCode = "200",
109 description = "Information type identifiers", //
110 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), //
112 public ResponseEntity<Object> getinfoTypeIdentifiers( //
114 List<String> result = new ArrayList<>();
115 for (InfoType infoType : this.infoTypes.getAllInfoTypes()) {
116 result.add(infoType.getId());
119 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
122 @GetMapping(path = "/info-types/{infoTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
123 @Operation(summary = "Individual information type", description = "")
127 responseCode = "200",
128 description = "Information type", //
129 content = @Content(schema = @Schema(implementation = ConsumerInfoTypeInfo.class))), //
131 responseCode = "404",
132 description = "Information type is not found", //
133 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
135 public ResponseEntity<Object> getInfoType( //
136 @PathVariable("infoTypeId") String infoTypeId) {
138 InfoType type = this.infoTypes.getType(infoTypeId);
139 ConsumerInfoTypeInfo info = toInfoTypeInfo(type);
140 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
141 } catch (Exception e) {
142 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
146 @GetMapping(path = "/info-jobs", produces = MediaType.APPLICATION_JSON_VALUE)
147 @Operation(summary = "Information Job identifiers", description = "query for information job identifiers")
151 responseCode = "200",
152 description = "Information information job identifiers", //
153 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
155 responseCode = "404",
156 description = "Information type is not found", //
157 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
159 public ResponseEntity<Object> getJobIds( //
161 name = ConsumerConsts.INFO_TYPE_ID_PARAM,
163 description = ConsumerConsts.INFO_TYPE_ID_PARAM_DESCRIPTION) //
164 @RequestParam(name = ConsumerConsts.INFO_TYPE_ID_PARAM, required = false) String infoTypeId,
166 name = ConsumerConsts.OWNER_PARAM,
168 description = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
169 @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
171 List<String> result = new ArrayList<>();
173 for (InfoJob job : this.jobs.getJobsForOwner(owner)) {
174 if (infoTypeId == null || job.getTypeId().equals(infoTypeId)) {
175 result.add(job.getId());
178 } else if (infoTypeId != null) {
179 this.jobs.getJobsForType(infoTypeId).forEach(job -> result.add(job.getId()));
181 this.jobs.getJobs().forEach(job -> result.add(job.getId()));
183 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
187 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
191 @GetMapping(path = "/info-jobs/{infoJobId}", produces = MediaType.APPLICATION_JSON_VALUE) //
192 @Operation(summary = ConsumerConsts.INDIVIDUAL_JOB, description = "") //
196 responseCode = "200",
197 description = "Information subscription job", //
198 content = @Content(schema = @Schema(implementation = ConsumerJobInfo.class))), //
200 responseCode = "404",
201 description = "Information subscription job is not found", //
202 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
204 public ResponseEntity<Object> getIndividualEiJob( //
205 @PathVariable("infoJobId") String infoJobId) {
207 InfoJob job = this.jobs.getJob(infoJobId);
208 return new ResponseEntity<>(gson.toJson(toInfoJobInfo(job)), HttpStatus.OK);
209 } catch (Exception e) {
210 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
214 @GetMapping(path = "/info-jobs/{infoJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
215 @Operation(summary = "Job status", description = "")
219 responseCode = "200",
220 description = "Information subscription job status", //
221 content = @Content(schema = @Schema(implementation = ConsumerJobStatus.class))), //
223 responseCode = "404",
224 description = "Information subscription job is not found", //
225 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
227 public ResponseEntity<Object> getEiJobStatus( //
228 @PathVariable("infoJobId") String jobId) {
230 InfoJob job = this.jobs.getJob(jobId);
231 return new ResponseEntity<>(gson.toJson(toInfoJobStatus(job)), HttpStatus.OK);
232 } catch (Exception e) {
233 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
237 private ConsumerJobStatus toInfoJobStatus(InfoJob job) {
238 Collection<String> producerIds = new ArrayList<>();
239 this.infoProducers.getProducersForType(job.getTypeId()).forEach(producer -> producerIds.add(producer.getId()));
240 return this.infoProducers.isJobEnabled(job)
241 ? new ConsumerJobStatus(ConsumerJobStatus.InfoJobStatusValues.ENABLED, producerIds)
242 : new ConsumerJobStatus(ConsumerJobStatus.InfoJobStatusValues.DISABLED, producerIds);
246 @DeleteMapping(path = "/info-jobs/{infoJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
247 @Operation(summary = ConsumerConsts.INDIVIDUAL_JOB, description = "")
251 responseCode = "200",
252 description = "Not used", //
253 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
255 responseCode = "204",
256 description = "Job deleted", //
257 content = @Content(schema = @Schema(implementation = VoidResponse.class))), // "Individual
260 responseCode = "404",
261 description = "Information subscription job is not found", //
262 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
264 public ResponseEntity<Object> deleteIndividualEiJob( //
265 @PathVariable("infoJobId") String jobId) {
267 InfoJob job = this.jobs.getJob(jobId);
268 this.jobs.remove(job, this.infoProducers);
269 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
270 } catch (Exception e) {
271 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
276 path = "/info-jobs/{infoJobId}", //
277 produces = MediaType.APPLICATION_JSON_VALUE, //
278 consumes = MediaType.APPLICATION_JSON_VALUE)
279 @Operation(summary = ConsumerConsts.INDIVIDUAL_JOB, description = ConsumerConsts.PUT_INDIVIDUAL_JOB_DESCRIPTION)
283 responseCode = "201",
284 description = "Job created", //
285 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
287 responseCode = "200",
288 description = "Job updated", //
289 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
291 responseCode = "404",
292 description = "Information type is not found", //
293 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
295 public Mono<ResponseEntity<Object>> putIndividualInfoJob( //
296 @PathVariable("infoJobId") String jobId, //
298 name = ConsumerConsts.PERFORM_TYPE_CHECK_PARAM,
300 description = ConsumerConsts.PERFORM_TYPE_CHECK_PARAM_DESCRIPTION) //
302 name = ConsumerConsts.PERFORM_TYPE_CHECK_PARAM,
304 defaultValue = "false") boolean performTypeCheck,
305 @RequestBody ConsumerJobInfo informationJobObject) {
307 final boolean isNewJob = this.jobs.get(jobId) == null;
309 return validatePutInfoJob(jobId, informationJobObject, performTypeCheck) //
310 .flatMap(this::startInfoSubscriptionJob) //
311 .doOnNext(newEiJob -> this.jobs.put(newEiJob)) //
312 .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
313 .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
316 @GetMapping(path = "/info-type-subscription", produces = MediaType.APPLICATION_JSON_VALUE)
318 summary = "Information type subscription identifiers",
319 description = "query for information type subscription identifiers")
323 responseCode = "200",
324 description = "Information type subscription identifiers", //
325 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),})
326 public ResponseEntity<Object> getInfoTypeSubscriptions( //
329 name = ConsumerConsts.OWNER_PARAM,
331 description = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
332 @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
334 List<String> result = new ArrayList<>();
336 this.infoTypeSubscriptions.getSubscriptionsForOwner(owner)
337 .forEach(subscription -> result.add(subscription.getId()));
339 this.infoTypeSubscriptions.getAllSubscriptions()
340 .forEach(subscription -> result.add(subscription.getId()));
342 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
343 } catch (Exception e) {
344 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
348 @GetMapping(path = "/info-type-subscription/{subscriptionId}", produces = MediaType.APPLICATION_JSON_VALUE) //
349 @Operation(summary = ConsumerConsts.INDIVIDUAL_TYPE_SUBSCRIPTION, description = "") //
353 responseCode = "200",
354 description = "Type subscription", //
355 content = @Content(schema = @Schema(implementation = ConsumerTypeSubscriptionInfo.class))), //
357 responseCode = "404",
358 description = "Subscription is not found", //
359 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
361 public ResponseEntity<Object> getIndividualTypeSubscription( //
362 @PathVariable("subscriptionId") String subscriptionId) {
364 InfoTypeSubscriptions.SubscriptionInfo subscription =
365 this.infoTypeSubscriptions.getSubscription(subscriptionId);
366 return new ResponseEntity<>(gson.toJson(toTypeSuscriptionInfo(subscription)), HttpStatus.OK);
367 } catch (Exception e) {
368 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
373 path = "/info-type-subscription/{subscriptionId}", //
374 produces = MediaType.APPLICATION_JSON_VALUE, //
375 consumes = MediaType.APPLICATION_JSON_VALUE)
377 summary = ConsumerConsts.INDIVIDUAL_TYPE_SUBSCRIPTION,
378 description = ConsumerConsts.TYPE_SUBSCRIPTION_DESCRIPTION)
382 responseCode = "201",
383 description = "Subscription created", //
384 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
386 responseCode = "200",
387 description = "Subscription updated", //
388 content = @Content(schema = @Schema(implementation = VoidResponse.class))) //
390 public Mono<ResponseEntity<Object>> putIndividualTypeSubscription( //
391 @PathVariable("subscriptionId") String subscriptionId, //
392 @RequestBody ConsumerTypeSubscriptionInfo subscription) {
394 final boolean isNewSubscription = this.infoTypeSubscriptions.get(subscriptionId) == null;
395 this.infoTypeSubscriptions.put(toTypeSuscriptionInfo(subscription, subscriptionId));
396 return Mono.just(new ResponseEntity<>(isNewSubscription ? HttpStatus.CREATED : HttpStatus.OK));
399 @DeleteMapping(path = "/info-type-subscription/{subscriptionId}", produces = MediaType.APPLICATION_JSON_VALUE)
400 @Operation(summary = ConsumerConsts.INDIVIDUAL_TYPE_SUBSCRIPTION, description = "")
404 responseCode = "200",
405 description = "Not used", //
406 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
408 responseCode = "204",
409 description = "Subscription deleted", //
410 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
412 responseCode = "404",
413 description = "Subscription is not found", //
414 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
416 public ResponseEntity<Object> deleteIndividualTypeSubscription( //
417 @PathVariable("subscriptionId") String subscriptionId) {
419 InfoTypeSubscriptions.SubscriptionInfo subscription =
420 this.infoTypeSubscriptions.getSubscription(subscriptionId);
421 this.infoTypeSubscriptions.remove(subscription);
422 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
423 } catch (Exception e) {
424 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
428 private ConsumerTypeSubscriptionInfo toTypeSuscriptionInfo(InfoTypeSubscriptions.SubscriptionInfo s) {
429 return new ConsumerTypeSubscriptionInfo(s.getCallbackUrl(), s.getOwner());
432 private InfoTypeSubscriptions.SubscriptionInfo toTypeSuscriptionInfo(ConsumerTypeSubscriptionInfo s,
433 String subscriptionId) {
434 return InfoTypeSubscriptions.SubscriptionInfo.builder() //
435 .callback(this.consumerCallbacks) //
437 .id(subscriptionId) //
438 .callbackUrl(s.statusResultUri).build();
442 private Mono<InfoJob> startInfoSubscriptionJob(InfoJob newInfoJob) {
443 return this.producerCallbacks.startInfoSubscriptionJob(newInfoJob, infoProducers) //
444 .doOnNext(noOfAcceptingProducers -> this.logger.debug("Started job {}, number of activated producers: {}",
445 newInfoJob.getId(), noOfAcceptingProducers)) //
446 .flatMap(noOfAcceptingProducers -> Mono.just(newInfoJob));
449 private Mono<InfoJob> validatePutInfoJob(String jobId, ConsumerJobInfo jobInfo, boolean performTypeCheck) {
451 if (performTypeCheck) {
452 InfoType infoType = this.infoTypes.getType(jobInfo.infoTypeId);
453 validateJsonObjectAgainstSchema(infoType.getJobDataSchema(), jobInfo.jobDefinition);
455 InfoJob existingEiJob = this.jobs.get(jobId);
456 validateUri(jobInfo.statusNotificationUri);
457 validateUri(jobInfo.jobResultUri);
459 if (existingEiJob != null && !existingEiJob.getTypeId().equals(jobInfo.infoTypeId)) {
460 throw new ServiceException("Not allowed to change type for existing job", HttpStatus.CONFLICT);
462 return Mono.just(toEiJob(jobInfo, jobId, jobInfo.infoTypeId));
463 } catch (Exception e) {
464 return Mono.error(e);
468 private void validateUri(String url) throws URISyntaxException, ServiceException {
469 if (url != null && !url.isEmpty()) {
470 URI uri = new URI(url);
471 if (!uri.isAbsolute()) {
472 throw new ServiceException("URI: " + url + " is not absolute", HttpStatus.CONFLICT);
477 private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
478 if (schemaObj != null) { // schema is optional for now
480 ObjectMapper mapper = new ObjectMapper();
482 String schemaAsString = mapper.writeValueAsString(schemaObj);
483 JSONObject schemaJSON = new JSONObject(schemaAsString);
484 var schema = org.everit.json.schema.loader.SchemaLoader.load(schemaJSON);
486 String objectAsString = mapper.writeValueAsString(object);
487 JSONObject json = new JSONObject(objectAsString);
488 schema.validate(json);
489 } catch (Exception e) {
490 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
495 private InfoJob toEiJob(ConsumerJobInfo info, String id, String typeId) {
496 return InfoJob.builder() //
499 .owner(info.owner) //
500 .jobData(info.jobDefinition) //
501 .targetUrl(info.jobResultUri) //
502 .jobStatusUrl(info.statusNotificationUri == null ? "" : info.statusNotificationUri) //
506 private ConsumerInfoTypeInfo toInfoTypeInfo(InfoType type) {
507 return new ConsumerInfoTypeInfo(type.getJobDataSchema(), typeStatus(type),
508 this.infoProducers.getProducerIdsForType(type.getId()).size());
511 private ConsumerInfoTypeInfo.ConsumerTypeStatusValues typeStatus(InfoType type) {
512 for (InfoProducer producer : this.infoProducers.getProducersForType(type)) {
513 if (producer.isAvailable()) {
514 return ConsumerInfoTypeInfo.ConsumerTypeStatusValues.ENABLED;
517 return ConsumerInfoTypeInfo.ConsumerTypeStatusValues.DISABLED;
520 private ConsumerJobInfo toInfoJobInfo(InfoJob s) {
521 return new ConsumerJobInfo(s.getTypeId(), s.getJobData(), s.getOwner(), s.getTargetUrl(), s.getJobStatusUrl());