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.InfoProducers;
52 import org.oransc.enrichment.repository.InfoType;
53 import org.oransc.enrichment.repository.InfoTypes;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.http.HttpStatus;
58 import org.springframework.http.MediaType;
59 import org.springframework.http.ResponseEntity;
60 import org.springframework.web.bind.annotation.DeleteMapping;
61 import org.springframework.web.bind.annotation.GetMapping;
62 import org.springframework.web.bind.annotation.PathVariable;
63 import org.springframework.web.bind.annotation.PutMapping;
64 import org.springframework.web.bind.annotation.RequestBody;
65 import org.springframework.web.bind.annotation.RequestMapping;
66 import org.springframework.web.bind.annotation.RequestParam;
67 import org.springframework.web.bind.annotation.RestController;
68 import reactor.core.publisher.Mono;
70 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
71 @RestController("Consumer registry")
72 @Tag(name = ConsumerConsts.CONSUMER_API_NAME)
73 @RequestMapping(path = ConsumerConsts.API_ROOT, produces = MediaType.APPLICATION_JSON_VALUE)
74 public class ConsumerController {
76 private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
79 ApplicationConfig applicationConfig;
82 private InfoJobs jobs;
85 private InfoTypes infoTypes;
88 private InfoProducers infoProducers;
91 ProducerCallbacks producerCallbacks;
93 private static Gson gson = new GsonBuilder().create();
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.jobs.getJobsForOwner(owner)) {
166 if (infoTypeId == null || job.getTypeId().equals(infoTypeId)) {
167 result.add(job.getId());
170 } else if (infoTypeId != null) {
171 this.jobs.getJobsForType(infoTypeId).forEach(job -> result.add(job.getId()));
173 this.jobs.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.jobs.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.jobs.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.jobs.getJob(jobId);
260 this.jobs.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.jobs.get(jobId) == null;
301 return validatePutInfoJob(jobId, informationJobObject, performTypeCheck) //
302 .flatMap(this::startInfoSubscriptionJob) //
303 .doOnNext(newEiJob -> this.jobs.put(newEiJob)) //
304 .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
305 .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
308 private Mono<InfoJob> startInfoSubscriptionJob(InfoJob newInfoJob) {
309 return this.producerCallbacks.startInfoSubscriptionJob(newInfoJob, infoProducers) //
310 .doOnNext(noOfAcceptingProducers -> this.logger.debug("Started job {}, number of activated producers: {}",
311 newInfoJob.getId(), noOfAcceptingProducers)) //
312 .flatMap(noOfAcceptingProducers -> Mono.just(newInfoJob));
315 private Mono<InfoJob> validatePutInfoJob(String jobId, ConsumerJobInfo jobInfo, boolean performTypeCheck) {
317 if (performTypeCheck) {
318 InfoType infoType = this.infoTypes.getType(jobInfo.infoTypeId);
319 validateJsonObjectAgainstSchema(infoType.getJobDataSchema(), jobInfo.jobDefinition);
321 InfoJob existingEiJob = this.jobs.get(jobId);
322 validateUri(jobInfo.statusNotificationUri);
323 validateUri(jobInfo.jobResultUri);
325 if (existingEiJob != null && !existingEiJob.getTypeId().equals(jobInfo.infoTypeId)) {
326 throw new ServiceException("Not allowed to change type for existing job", HttpStatus.CONFLICT);
328 return Mono.just(toEiJob(jobInfo, jobId, jobInfo.infoTypeId));
329 } catch (Exception e) {
330 return Mono.error(e);
334 private void validateUri(String url) throws URISyntaxException, ServiceException {
335 if (url != null && !url.isEmpty()) {
336 URI uri = new URI(url);
337 if (!uri.isAbsolute()) {
338 throw new ServiceException("URI: " + url + " is not absolute", HttpStatus.CONFLICT);
343 private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
344 if (schemaObj != null) { // schema is optional for now
346 ObjectMapper mapper = new ObjectMapper();
348 String schemaAsString = mapper.writeValueAsString(schemaObj);
349 JSONObject schemaJSON = new JSONObject(schemaAsString);
350 var schema = org.everit.json.schema.loader.SchemaLoader.load(schemaJSON);
352 String objectAsString = mapper.writeValueAsString(object);
353 JSONObject json = new JSONObject(objectAsString);
354 schema.validate(json);
355 } catch (Exception e) {
356 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
361 private InfoJob toEiJob(ConsumerJobInfo info, String id, String typeId) {
362 return InfoJob.builder() //
365 .owner(info.owner) //
366 .jobData(info.jobDefinition) //
367 .targetUrl(info.jobResultUri) //
368 .jobStatusUrl(info.statusNotificationUri == null ? "" : info.statusNotificationUri) //
372 private ConsumerInfoTypeInfo toInfoTypeInfo(InfoType type) {
373 return new ConsumerInfoTypeInfo(type.getJobDataSchema());
376 private ConsumerJobInfo toInfoJobInfo(InfoJob s) {
377 return new ConsumerJobInfo(s.getTypeId(), s.getJobData(), s.getOwner(), s.getTargetUrl(), s.getJobStatusUrl());