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.consumer;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
27 import io.swagger.annotations.Api;
28 import io.swagger.annotations.ApiOperation;
29 import io.swagger.annotations.ApiParam;
30 import io.swagger.annotations.ApiResponse;
31 import io.swagger.annotations.ApiResponses;
33 import java.util.ArrayList;
34 import java.util.Collection;
35 import java.util.List;
37 import org.everit.json.schema.Schema;
38 import org.everit.json.schema.loader.SchemaLoader;
39 import org.json.JSONObject;
40 import org.oransc.enrichment.configuration.ApplicationConfig;
41 import org.oransc.enrichment.controllers.ErrorResponse;
42 import org.oransc.enrichment.controllers.VoidResponse;
43 import org.oransc.enrichment.controllers.producer.ProducerCallbacks;
44 import org.oransc.enrichment.exceptions.ServiceException;
45 import org.oransc.enrichment.repository.EiJob;
46 import org.oransc.enrichment.repository.EiJobs;
47 import org.oransc.enrichment.repository.EiProducer;
48 import org.oransc.enrichment.repository.EiProducers;
49 import org.oransc.enrichment.repository.EiType;
50 import org.oransc.enrichment.repository.EiTypes;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.http.HttpStatus;
53 import org.springframework.http.MediaType;
54 import org.springframework.http.ResponseEntity;
55 import org.springframework.web.bind.annotation.DeleteMapping;
56 import org.springframework.web.bind.annotation.GetMapping;
57 import org.springframework.web.bind.annotation.PathVariable;
58 import org.springframework.web.bind.annotation.PutMapping;
59 import org.springframework.web.bind.annotation.RequestBody;
60 import org.springframework.web.bind.annotation.RequestMapping;
61 import org.springframework.web.bind.annotation.RequestParam;
62 import org.springframework.web.bind.annotation.RestController;
63 import reactor.core.publisher.Mono;
65 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
66 @RestController("ConsumerController")
67 @Api(tags = {ConsumerConsts.CONSUMER_API_NAME})
68 @RequestMapping(path = ConsumerConsts.API_ROOT, produces = MediaType.APPLICATION_JSON_VALUE)
69 public class ConsumerController {
72 ApplicationConfig applicationConfig;
75 private EiJobs eiJobs;
78 private EiTypes eiTypes;
81 private EiProducers eiProducers;
84 ProducerCallbacks producerCallbacks;
86 private static Gson gson = new GsonBuilder().create();
88 @GetMapping(path = "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
89 @ApiOperation(value = "EI type identifiers", notes = "")
94 message = "EI type identifiers",
95 response = String.class,
96 responseContainer = "List"), //
98 public ResponseEntity<Object> getEiTypeIdentifiers( //
100 List<String> result = new ArrayList<>();
101 for (EiType eiType : this.eiTypes.getAllEiTypes()) {
102 result.add(eiType.getId());
105 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
108 @GetMapping(path = "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
109 @ApiOperation(value = "Individual EI type", notes = "")
112 @ApiResponse(code = 200, message = "EI type", response = ConsumerEiTypeInfo.class), //
115 message = "Enrichment Information type is not found",
116 response = ErrorResponse.ErrorInfo.class)})
117 public ResponseEntity<Object> getEiType( //
118 @PathVariable("eiTypeId") String eiTypeId) {
120 this.eiTypes.getType(eiTypeId); // Make sure that the type exists
121 ConsumerEiTypeInfo info = toEiTypeInfo();
122 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
123 } catch (Exception e) {
124 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
128 @GetMapping(path = "/eijobs", produces = MediaType.APPLICATION_JSON_VALUE)
129 @ApiOperation(value = "EI job identifiers", notes = "query for EI job identifiers")
134 message = "EI job identifiers",
135 response = String.class,
136 responseContainer = "List"), //
139 message = "Enrichment Information type is not found",
140 response = ErrorResponse.ErrorInfo.class)})
141 public ResponseEntity<Object> getEiJobIds( //
143 name = ConsumerConsts.EI_TYPE_ID_PARAM,
145 value = ConsumerConsts.EI_TYPE_ID_PARAM_DESCRIPTION) //
146 @RequestParam(name = ConsumerConsts.EI_TYPE_ID_PARAM, required = false) String eiTypeId,
148 name = ConsumerConsts.OWNER_PARAM,
150 value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
151 @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
153 List<String> result = new ArrayList<>();
155 for (EiJob job : this.eiJobs.getJobsForOwner(owner)) {
156 if (eiTypeId == null || job.getTypeId().equals(eiTypeId)) {
157 result.add(job.getId());
160 } else if (eiTypeId != null) {
161 this.eiJobs.getJobsForType(eiTypeId).forEach(job -> result.add(job.getId()));
163 this.eiJobs.getJobs().forEach(job -> result.add(job.getId()));
165 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
169 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
173 @GetMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
174 @ApiOperation(value = "Individual EI job", notes = "")
177 @ApiResponse(code = 200, message = "EI job", response = ConsumerEiJobInfo.class), //
180 message = "Enrichment Information job is not found",
181 response = ErrorResponse.ErrorInfo.class)})
182 public ResponseEntity<Object> getIndividualEiJob( //
183 @PathVariable("eiJobId") String eiJobId) {
185 EiJob job = this.eiJobs.getJob(eiJobId);
186 return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
187 } catch (Exception e) {
188 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
192 @GetMapping(path = "/eijobs/{eiJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
193 @ApiOperation(value = "EI job status", notes = "")
196 @ApiResponse(code = 200, message = "EI job status", response = ConsumerEiJobStatus.class), //
199 message = "Enrichment Information job is not found",
200 response = ErrorResponse.ErrorInfo.class)})
201 public ResponseEntity<Object> getEiJobStatus( //
202 @PathVariable("eiJobId") String eiJobId) {
204 EiJob job = this.eiJobs.getJob(eiJobId);
205 return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
206 } catch (Exception e) {
207 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
211 private Collection<EiProducer> getProducers(EiJob eiJob) {
212 return this.eiProducers.getProducersForType(eiJob.getTypeId());
215 private ConsumerEiJobStatus toEiJobStatus(EiJob job) {
216 if (getProducers(job).isEmpty()) {
217 return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.DISABLED);
219 return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.ENABLED);
223 @DeleteMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
224 @ApiOperation(value = "Individual EI job", notes = "")
227 @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
228 @ApiResponse(code = 204, message = "Job deleted", response = VoidResponse.class),
231 message = "Enrichment Information job is not found",
232 response = ErrorResponse.ErrorInfo.class)})
233 public ResponseEntity<Object> deleteIndividualEiJob( //
234 @PathVariable("eiJobId") String eiJobId) {
236 EiJob job = this.eiJobs.getJob(eiJobId);
237 this.eiJobs.remove(job, this.eiProducers);
238 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
239 } catch (Exception e) {
240 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
245 path = "/eijobs/{eiJobId}", //
246 produces = MediaType.APPLICATION_JSON_VALUE, //
247 consumes = MediaType.APPLICATION_JSON_VALUE)
248 @ApiOperation(value = "Individual EI job", notes = "")
251 @ApiResponse(code = 201, message = "Job created", response = VoidResponse.class), //
252 @ApiResponse(code = 200, message = "Job updated", response = VoidResponse.class), // ,
255 message = "Enrichment Information type is not found",
256 response = ErrorResponse.ErrorInfo.class)})
257 public Mono<ResponseEntity<Object>> putIndividualEiJob( //
258 @PathVariable("eiJobId") String eiJobId, //
259 @RequestBody ConsumerEiJobInfo eiJobObject) {
261 final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
263 return validatePutEiJob(eiJobId, eiJobObject) //
264 .flatMap(this::startEiJob) //
265 .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
266 .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
267 .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
270 private Mono<EiJob> startEiJob(EiJob newEiJob) {
271 return this.producerCallbacks.startEiJob(newEiJob, eiProducers) //
272 .flatMap(noOfAcceptingProducers -> {
273 if (noOfAcceptingProducers.intValue() > 0) {
274 return Mono.just(newEiJob);
276 return Mono.error(new ServiceException("Job not accepted by any producers", HttpStatus.CONFLICT));
281 private Mono<EiJob> validatePutEiJob(String eiJobId, ConsumerEiJobInfo eiJobInfo) {
283 EiType eiType = this.eiTypes.getType(eiJobInfo.eiTypeId);
284 validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobData);
285 EiJob existingEiJob = this.eiJobs.get(eiJobId);
287 if (existingEiJob != null && !existingEiJob.getTypeId().equals(eiJobInfo.eiTypeId)) {
288 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
290 return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
291 } catch (Exception e) {
292 return Mono.error(e);
296 private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
297 if (schemaObj != null) { // schema is optional for now
299 ObjectMapper mapper = new ObjectMapper();
301 String schemaAsString = mapper.writeValueAsString(schemaObj);
302 JSONObject schemaJSON = new JSONObject(schemaAsString);
303 Schema schema = SchemaLoader.load(schemaJSON);
305 String objectAsString = mapper.writeValueAsString(object);
306 JSONObject json = new JSONObject(objectAsString);
307 schema.validate(json);
308 } catch (Exception e) {
309 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
314 private EiJob toEiJob(ConsumerEiJobInfo info, String id, EiType type) {
315 return EiJob.builder() //
317 .typeId(type.getId()) //
318 .owner(info.owner) //
319 .jobData(info.jobData) //
320 .targetUrl(info.targetUri) //
321 .jobStatusUrl(info.statusNotificationUri == null ? "" : info.statusNotificationUri) //
325 private ConsumerEiTypeInfo toEiTypeInfo() {
326 return new ConsumerEiTypeInfo();
329 private ConsumerEiJobInfo toEiJobInfo(EiJob s) {
330 return new ConsumerEiJobInfo(s.getTypeId(), s.getJobData(), s.getOwner(), s.getTargetUrl(),
331 s.getJobStatusUrl());