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;
36 import java.util.Vector;
38 import org.everit.json.schema.Schema;
39 import org.everit.json.schema.loader.SchemaLoader;
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.producer.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.EiProducer;
49 import org.oransc.enrichment.repository.EiType;
50 import org.oransc.enrichment.repository.EiTypes;
51 import org.oransc.enrichment.repository.ImmutableEiJob;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.http.HttpStatus;
54 import org.springframework.http.MediaType;
55 import org.springframework.http.ResponseEntity;
56 import org.springframework.web.bind.annotation.DeleteMapping;
57 import org.springframework.web.bind.annotation.GetMapping;
58 import org.springframework.web.bind.annotation.PathVariable;
59 import org.springframework.web.bind.annotation.PutMapping;
60 import org.springframework.web.bind.annotation.RequestBody;
61 import org.springframework.web.bind.annotation.RequestMapping;
62 import org.springframework.web.bind.annotation.RequestParam;
63 import org.springframework.web.bind.annotation.RestController;
64 import reactor.core.publisher.Mono;
66 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
67 @RestController("ConsumerController")
68 @Api(tags = {ConsumerConsts.CONSUMER_API_NAME})
69 @RequestMapping(path = ConsumerConsts.API_ROOT, produces = MediaType.APPLICATION_JSON_VALUE)
70 public class ConsumerController {
73 ApplicationConfig applicationConfig;
76 private EiJobs eiJobs;
79 private EiTypes eiTypes;
82 ProducerCallbacks producerCallbacks;
84 private static Gson gson = new GsonBuilder().create();
86 @GetMapping(path = "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
87 @ApiOperation(value = "EI type identifiers", notes = "")
92 message = "EI type identifiers",
93 response = String.class,
94 responseContainer = "List"), //
96 public ResponseEntity<Object> getEiTypeIdentifiers( //
98 List<String> result = new ArrayList<>();
99 for (EiType eiType : this.eiTypes.getAllEiTypes()) {
100 result.add(eiType.getId());
103 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
106 @GetMapping(path = "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
107 @ApiOperation(value = "Individual EI type", notes = "")
110 @ApiResponse(code = 200, message = "EI type", response = ConsumerEiTypeInfo.class), //
113 message = "Enrichment Information type is not found",
114 response = ErrorResponse.ErrorInfo.class)})
115 public ResponseEntity<Object> getEiType( //
116 @PathVariable("eiTypeId") String eiTypeId) {
118 this.eiTypes.getType(eiTypeId); // Make sure that the type exists
119 ConsumerEiTypeInfo info = toEiTypeInfo();
120 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
121 } catch (Exception e) {
122 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
126 @GetMapping(path = "/eijobs", produces = MediaType.APPLICATION_JSON_VALUE)
127 @ApiOperation(value = "EI job identifiers", notes = "query for EI job identifiers")
132 message = "EI job identifiers",
133 response = String.class,
134 responseContainer = "List"), //
137 message = "Enrichment Information type is not found",
138 response = ErrorResponse.ErrorInfo.class)})
139 public ResponseEntity<Object> getEiJobIds( //
141 name = ConsumerConsts.EI_TYPE_ID_PARAM,
143 value = ConsumerConsts.EI_TYPE_ID_PARAM_DESCRIPTION) //
144 @RequestParam(name = ConsumerConsts.EI_TYPE_ID_PARAM, required = false) String eiTypeId,
146 name = ConsumerConsts.OWNER_PARAM,
148 value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
149 @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
151 List<String> result = new ArrayList<>();
153 for (EiJob job : this.eiJobs.getJobsForOwner(owner)) {
154 if (eiTypeId == null || job.typeId().equals(eiTypeId)) {
155 result.add(job.id());
158 } else if (eiTypeId != null) {
159 this.eiJobs.getJobsForType(eiTypeId).forEach(job -> result.add(job.id()));
161 this.eiJobs.getJobs().forEach(job -> result.add(job.id()));
163 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
167 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
171 @GetMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
172 @ApiOperation(value = "Individual EI job", notes = "")
175 @ApiResponse(code = 200, message = "EI job", response = ConsumerEiJobInfo.class), //
178 message = "Enrichment Information job is not found",
179 response = ErrorResponse.ErrorInfo.class)})
180 public ResponseEntity<Object> getIndividualEiJob( //
181 @PathVariable("eiJobId") String eiJobId) {
183 EiJob job = this.eiJobs.getJob(eiJobId);
184 return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
185 } catch (Exception e) {
186 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
190 @GetMapping(path = "/eijobs/{eiJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
191 @ApiOperation(value = "EI job status", notes = "")
194 @ApiResponse(code = 200, message = "EI job status", response = ConsumerEiJobStatus.class), //
197 message = "Enrichment Information job is not found",
198 response = ErrorResponse.ErrorInfo.class)})
199 public ResponseEntity<Object> getEiJobStatus( //
200 @PathVariable("eiJobId") String eiJobId) {
202 EiJob job = this.eiJobs.getJob(eiJobId);
203 return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
204 } catch (Exception e) {
205 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
209 private Collection<EiProducer> getProducers(EiJob eiJob) {
211 return this.eiTypes.getType(eiJob.typeId()).getProducers();
212 } catch (Exception e) {
213 return new Vector<>();
217 private ConsumerEiJobStatus toEiJobStatus(EiJob job) {
218 for (EiProducer producer : getProducers(job)) {
219 if (producer.isAvailable()) {
220 return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.ENABLED);
223 return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.DISABLED);
226 @DeleteMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
227 @ApiOperation(value = "Individual EI job", notes = "")
230 @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
231 @ApiResponse(code = 204, message = "Job deleted", response = VoidResponse.class),
234 message = "Enrichment Information job is not found",
235 response = ErrorResponse.ErrorInfo.class)})
236 public ResponseEntity<Object> deleteIndividualEiJob( //
237 @PathVariable("eiJobId") String eiJobId) {
239 EiJob job = this.eiJobs.getJob(eiJobId);
240 this.eiJobs.remove(job);
241 this.producerCallbacks.notifyProducersJobDeleted(job);
242 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
243 } catch (Exception e) {
244 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
249 path = "/eijobs/{eiJobId}", //
250 produces = MediaType.APPLICATION_JSON_VALUE, //
251 consumes = MediaType.APPLICATION_JSON_VALUE)
252 @ApiOperation(value = "Individual EI job", notes = "")
255 @ApiResponse(code = 201, message = "Job created", response = VoidResponse.class), //
256 @ApiResponse(code = 200, message = "Job updated", response = VoidResponse.class), // ,
259 message = "Enrichment Information type is not found",
260 response = ErrorResponse.ErrorInfo.class)})
261 public Mono<ResponseEntity<Object>> putIndividualEiJob( //
262 @PathVariable("eiJobId") String eiJobId, //
263 @RequestBody ConsumerEiJobInfo eiJobObject) {
265 final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
267 return validatePutEiJob(eiJobId, eiJobObject) //
268 .flatMap(this::notifyProducersNewJob) //
269 .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
270 .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
271 .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
274 private Mono<EiJob> notifyProducersNewJob(EiJob newEiJob) {
275 return this.producerCallbacks.notifyProducersJobStarted(newEiJob) //
276 .flatMap(noOfAcceptingProducers -> {
277 if (noOfAcceptingProducers.intValue() > 0) {
278 return Mono.just(newEiJob);
280 return Mono.error(new ServiceException("Job not accepted by any producers", HttpStatus.CONFLICT));
285 private Mono<EiJob> validatePutEiJob(String eiJobId, ConsumerEiJobInfo eiJobInfo) {
287 EiType eiType = this.eiTypes.getType(eiJobInfo.eiTypeId);
288 validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobData);
289 EiJob existingEiJob = this.eiJobs.get(eiJobId);
291 if (existingEiJob != null && !existingEiJob.typeId().equals(eiJobInfo.eiTypeId)) {
292 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
294 return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
295 } catch (Exception e) {
296 return Mono.error(e);
300 private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
301 if (schemaObj != null) { // schema is optional for now
303 ObjectMapper mapper = new ObjectMapper();
305 String schemaAsString = mapper.writeValueAsString(schemaObj);
306 JSONObject schemaJSON = new JSONObject(schemaAsString);
307 Schema schema = SchemaLoader.load(schemaJSON);
309 String objectAsString = mapper.writeValueAsString(object);
310 JSONObject json = new JSONObject(objectAsString);
311 schema.validate(json);
312 } catch (Exception e) {
313 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
318 private EiJob toEiJob(ConsumerEiJobInfo info, String id, EiType type) {
319 return ImmutableEiJob.builder() //
321 .typeId(type.getId()) //
322 .owner(info.owner) //
323 .jobData(info.jobData) //
324 .targetUrl(info.targetUri) //
325 .jobStatusUrl(info.statusNotificationUri == null ? "" : info.statusNotificationUri) //
329 private ConsumerEiTypeInfo toEiTypeInfo() {
330 return new ConsumerEiTypeInfo();
333 private ConsumerEiJobInfo toEiJobInfo(EiJob s) {
334 return new ConsumerEiJobInfo(s.typeId(), s.jobData(), s.owner(), s.targetUrl(), s.jobStatusUrl());