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;
37 import java.util.ArrayList;
38 import java.util.List;
40 import org.json.JSONObject;
41 import org.oransc.enrichment.configuration.ApplicationConfig;
42 import org.oransc.enrichment.controllers.ErrorResponse;
43 import org.oransc.enrichment.controllers.VoidResponse;
44 import org.oransc.enrichment.controllers.r1producer.ProducerCallbacks;
45 import org.oransc.enrichment.exceptions.ServiceException;
46 import org.oransc.enrichment.repository.EiJob;
47 import org.oransc.enrichment.repository.EiJobs;
48 import org.oransc.enrichment.repository.EiProducers;
49 import org.oransc.enrichment.repository.EiType;
50 import org.oransc.enrichment.repository.EiTypes;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.http.HttpStatus;
55 import org.springframework.http.MediaType;
56 import org.springframework.http.ResponseEntity;
57 import org.springframework.web.bind.annotation.DeleteMapping;
58 import org.springframework.web.bind.annotation.GetMapping;
59 import org.springframework.web.bind.annotation.PathVariable;
60 import org.springframework.web.bind.annotation.PutMapping;
61 import org.springframework.web.bind.annotation.RequestBody;
62 import org.springframework.web.bind.annotation.RequestMapping;
63 import org.springframework.web.bind.annotation.RequestParam;
64 import org.springframework.web.bind.annotation.RestController;
65 import reactor.core.publisher.Mono;
67 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
68 @RestController("Consumer registry")
69 @Tag(name = ConsumerConsts.CONSUMER_API_NAME)
70 @RequestMapping(path = ConsumerConsts.API_ROOT, produces = MediaType.APPLICATION_JSON_VALUE)
71 public class ConsumerController {
73 private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
76 ApplicationConfig applicationConfig;
82 private EiTypes infoTypes;
85 private EiProducers infoProducers;
88 ProducerCallbacks producerCallbacks;
90 private static Gson gson = new GsonBuilder().create();
92 @GetMapping(path = "/info-types", produces = MediaType.APPLICATION_JSON_VALUE)
93 @Operation(summary = "Information type identifiers", description = "")
98 description = "Information type identifiers", //
99 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), //
101 public ResponseEntity<Object> getinfoTypeIdentifiers( //
103 List<String> result = new ArrayList<>();
104 for (EiType infoType : this.infoTypes.getAllInfoTypes()) {
105 result.add(infoType.getId());
108 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
111 @GetMapping(path = "/info-types/{infoTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
112 @Operation(summary = "Individual information type", description = "")
116 responseCode = "200",
117 description = "Information type", //
118 content = @Content(schema = @Schema(implementation = ConsumerInfoTypeInfo.class))), //
120 responseCode = "404",
121 description = "Information type is not found", //
122 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
124 public ResponseEntity<Object> getInfoType( //
125 @PathVariable("infoTypeId") String infoTypeId) {
127 EiType type = this.infoTypes.getType(infoTypeId);
128 ConsumerInfoTypeInfo info = toInfoTypeInfo(type);
129 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
130 } catch (Exception e) {
131 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
135 @GetMapping(path = "/info-jobs", produces = MediaType.APPLICATION_JSON_VALUE)
136 @Operation(summary = "EI job identifiers", description = "query for information job identifiers")
140 responseCode = "200",
141 description = "Information information job identifiers", //
142 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
144 responseCode = "404",
145 description = "Information type is not found", //
146 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
148 public ResponseEntity<Object> getJobIds( //
150 name = ConsumerConsts.INFO_TYPE_ID_PARAM,
152 description = ConsumerConsts.INFO_TYPE_ID_PARAM_DESCRIPTION) //
153 @RequestParam(name = ConsumerConsts.INFO_TYPE_ID_PARAM, required = false) String infoTypeId,
155 name = ConsumerConsts.OWNER_PARAM,
157 description = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
158 @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
160 List<String> result = new ArrayList<>();
162 for (EiJob job : this.jobs.getJobsForOwner(owner)) {
163 if (infoTypeId == null || job.getTypeId().equals(infoTypeId)) {
164 result.add(job.getId());
167 } else if (infoTypeId != null) {
168 this.jobs.getJobsForType(infoTypeId).forEach(job -> result.add(job.getId()));
170 this.jobs.getJobs().forEach(job -> result.add(job.getId()));
172 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
176 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
180 @GetMapping(path = "/info-jobs/{infoJobId}", produces = MediaType.APPLICATION_JSON_VALUE) //
181 @Operation(summary = ConsumerConsts.INDIVIDUAL_JOB, description = "") //
185 responseCode = "200",
186 description = "Information subscription job", //
187 content = @Content(schema = @Schema(implementation = ConsumerJobInfo.class))), //
189 responseCode = "404",
190 description = "Information subscription job is not found", //
191 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
193 public ResponseEntity<Object> getIndividualEiJob( //
194 @PathVariable("infoJobId") String infoJobId) {
196 EiJob job = this.jobs.getJob(infoJobId);
197 return new ResponseEntity<>(gson.toJson(toInfoJobInfo(job)), HttpStatus.OK);
198 } catch (Exception e) {
199 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
203 @GetMapping(path = "/info-jobs/{infoJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
204 @Operation(summary = "Job status", description = "")
208 responseCode = "200",
209 description = "Information subscription job status", //
210 content = @Content(schema = @Schema(implementation = ConsumerJobStatus.class))), //
212 responseCode = "404",
213 description = "Information subscription job is not found", //
214 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
216 public ResponseEntity<Object> getEiJobStatus( //
217 @PathVariable("infoJobId") String jobId) {
219 EiJob job = this.jobs.getJob(jobId);
220 return new ResponseEntity<>(gson.toJson(toInfoJobStatus(job)), HttpStatus.OK);
221 } catch (Exception e) {
222 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
226 private ConsumerJobStatus toInfoJobStatus(EiJob job) {
227 return this.infoProducers.isJobEnabled(job)
228 ? new ConsumerJobStatus(ConsumerJobStatus.InfoJobStatusValues.ENABLED)
229 : new ConsumerJobStatus(ConsumerJobStatus.InfoJobStatusValues.DISABLED);
233 @DeleteMapping(path = "/info-jobs/{infoJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
234 @Operation(summary = ConsumerConsts.INDIVIDUAL_JOB, description = "")
238 responseCode = "200",
239 description = "Not used", //
240 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
242 responseCode = "204",
243 description = "Job deleted", //
244 content = @Content(schema = @Schema(implementation = VoidResponse.class))), // "Individual EI job"
246 responseCode = "404",
247 description = "Information subscription job is not found", //
248 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
250 public ResponseEntity<Object> deleteIndividualEiJob( //
251 @PathVariable("infoJobId") String jobId) {
253 EiJob job = this.jobs.getJob(jobId);
254 this.jobs.remove(job, this.infoProducers);
255 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
256 } catch (Exception e) {
257 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
262 path = "/info-jobs/{infoJobId}", //
263 produces = MediaType.APPLICATION_JSON_VALUE, //
264 consumes = MediaType.APPLICATION_JSON_VALUE)
265 @Operation(summary = ConsumerConsts.INDIVIDUAL_JOB)
269 responseCode = "201",
270 description = "Job created", //
271 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
273 responseCode = "200",
274 description = "Job updated", //
275 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
277 responseCode = "404",
278 description = "Enrichment Information type is not found", //
279 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
281 public Mono<ResponseEntity<Object>> putIndividualInfoJob( //
282 @PathVariable("infoJobId") String jobId, //
283 @RequestBody ConsumerJobInfo informationJobObject) {
285 final boolean isNewJob = this.jobs.get(jobId) == null;
287 return validatePutInfoJob(jobId, informationJobObject) //
288 .flatMap(this::startInfoSubscriptionJob) //
289 .doOnNext(newEiJob -> this.jobs.put(newEiJob)) //
290 .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
291 .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
294 private Mono<EiJob> startInfoSubscriptionJob(EiJob newInfoJob) {
295 return this.producerCallbacks.startInfoSubscriptionJob(newInfoJob, infoProducers) //
296 .doOnNext(noOfAcceptingProducers -> this.logger.debug("Started job {}, number of activated producers: {}",
297 newInfoJob.getId(), noOfAcceptingProducers)) //
298 .flatMap(noOfAcceptingProducers -> Mono.just(newInfoJob));
301 private Mono<EiJob> validatePutInfoJob(String jobId, ConsumerJobInfo jobInfo) {
303 EiType infoType = this.infoTypes.getType(jobInfo.infoTypeId);
304 validateJsonObjectAgainstSchema(infoType.getJobDataSchema(), jobInfo.jobDefinition);
305 EiJob existingEiJob = this.jobs.get(jobId);
307 if (existingEiJob != null && !existingEiJob.getTypeId().equals(jobInfo.infoTypeId)) {
308 throw new ServiceException("Not allowed to change type for existing job", HttpStatus.CONFLICT);
310 return Mono.just(toEiJob(jobInfo, jobId, infoType));
311 } catch (Exception e) {
312 return Mono.error(e);
316 private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
317 if (schemaObj != null) { // schema is optional for now
319 ObjectMapper mapper = new ObjectMapper();
321 String schemaAsString = mapper.writeValueAsString(schemaObj);
322 JSONObject schemaJSON = new JSONObject(schemaAsString);
323 org.everit.json.schema.Schema schema = org.everit.json.schema.loader.SchemaLoader.load(schemaJSON);
325 String objectAsString = mapper.writeValueAsString(object);
326 JSONObject json = new JSONObject(objectAsString);
327 schema.validate(json);
328 } catch (Exception e) {
329 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
334 private EiJob toEiJob(ConsumerJobInfo info, String id, EiType type) {
335 return EiJob.builder() //
337 .typeId(type.getId()) //
338 .owner(info.owner) //
339 .jobData(info.jobDefinition) //
340 .targetUrl(info.jobResultUri) //
341 .jobStatusUrl(info.statusNotificationUri == null ? "" : info.statusNotificationUri) //
345 private ConsumerInfoTypeInfo toInfoTypeInfo(EiType type) {
346 return new ConsumerInfoTypeInfo(type.getJobDataSchema());
349 private ConsumerJobInfo toInfoJobInfo(EiJob s) {
350 return new ConsumerJobInfo(s.getTypeId(), s.getJobData(), s.getOwner(), s.getTargetUrl(), s.getJobStatusUrl());