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.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 ProducerCallbacks producerCallbacks;
83 private static Gson gson = new GsonBuilder().create();
85 @GetMapping(path = "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
86 @ApiOperation(value = "EI type identifiers", notes = "")
91 message = "EI type identifiers",
92 response = String.class,
93 responseContainer = "List"), //
95 public ResponseEntity<Object> getEiTypeIdentifiers( //
97 List<String> result = new ArrayList<>();
98 for (EiType eiType : this.eiTypes.getAllEiTypes()) {
99 result.add(eiType.getId());
102 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
105 @GetMapping(path = "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
106 @ApiOperation(value = "Individual EI type", notes = "")
109 @ApiResponse(code = 200, message = "EI type", response = ConsumerEiTypeInfo.class), //
112 message = "Enrichment Information type is not found",
113 response = ErrorResponse.ErrorInfo.class)})
114 public ResponseEntity<Object> getEiType( //
115 @PathVariable("eiTypeId") String eiTypeId) {
117 this.eiTypes.getType(eiTypeId); // Make sure that the type exists
118 ConsumerEiTypeInfo info = toEiTypeInfo();
119 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
120 } catch (Exception e) {
121 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
125 @GetMapping(path = "/eijobs", produces = MediaType.APPLICATION_JSON_VALUE)
126 @ApiOperation(value = "EI job identifiers", notes = "query for EI job identifiers")
131 message = "EI job identifiers",
132 response = String.class,
133 responseContainer = "List"), //
136 message = "Enrichment Information type is not found",
137 response = ErrorResponse.ErrorInfo.class)})
138 public ResponseEntity<Object> getEiJobIds( //
140 name = ConsumerConsts.EI_TYPE_ID_PARAM,
142 value = ConsumerConsts.EI_TYPE_ID_PARAM_DESCRIPTION) //
143 @RequestParam(name = ConsumerConsts.EI_TYPE_ID_PARAM, required = false) String eiTypeId,
145 name = ConsumerConsts.OWNER_PARAM,
147 value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
148 @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
150 List<String> result = new ArrayList<>();
152 for (EiJob job : this.eiJobs.getJobsForOwner(owner)) {
153 if (eiTypeId == null || job.getTypeId().equals(eiTypeId)) {
154 result.add(job.getId());
157 } else if (eiTypeId != null) {
158 this.eiJobs.getJobsForType(eiTypeId).forEach(job -> result.add(job.getId()));
160 this.eiJobs.getJobs().forEach(job -> result.add(job.getId()));
162 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
166 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
170 @GetMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
171 @ApiOperation(value = "Individual EI job", notes = "")
174 @ApiResponse(code = 200, message = "EI job", response = ConsumerEiJobInfo.class), //
177 message = "Enrichment Information job is not found",
178 response = ErrorResponse.ErrorInfo.class)})
179 public ResponseEntity<Object> getIndividualEiJob( //
180 @PathVariable("eiJobId") String eiJobId) {
182 EiJob job = this.eiJobs.getJob(eiJobId);
183 return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
184 } catch (Exception e) {
185 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
189 @GetMapping(path = "/eijobs/{eiJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
190 @ApiOperation(value = "EI job status", notes = "")
193 @ApiResponse(code = 200, message = "EI job status", response = ConsumerEiJobStatus.class), //
196 message = "Enrichment Information job is not found",
197 response = ErrorResponse.ErrorInfo.class)})
198 public ResponseEntity<Object> getEiJobStatus( //
199 @PathVariable("eiJobId") String eiJobId) {
201 EiJob job = this.eiJobs.getJob(eiJobId);
202 return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
203 } catch (Exception e) {
204 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
208 private Collection<EiProducer> getProducers(EiJob eiJob) {
210 return this.eiTypes.getType(eiJob.getTypeId()).getProducers();
211 } catch (Exception e) {
212 return new Vector<>();
216 private ConsumerEiJobStatus toEiJobStatus(EiJob job) {
217 if (getProducers(job).isEmpty()) {
218 return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.DISABLED);
220 return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.ENABLED);
224 @DeleteMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
225 @ApiOperation(value = "Individual EI job", notes = "")
228 @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
229 @ApiResponse(code = 204, message = "Job deleted", response = VoidResponse.class),
232 message = "Enrichment Information job is not found",
233 response = ErrorResponse.ErrorInfo.class)})
234 public ResponseEntity<Object> deleteIndividualEiJob( //
235 @PathVariable("eiJobId") String eiJobId) {
237 EiJob job = this.eiJobs.getJob(eiJobId);
238 this.eiJobs.remove(job);
239 this.producerCallbacks.notifyProducersJobDeleted(job);
240 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
241 } catch (Exception e) {
242 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
247 path = "/eijobs/{eiJobId}", //
248 produces = MediaType.APPLICATION_JSON_VALUE, //
249 consumes = MediaType.APPLICATION_JSON_VALUE)
250 @ApiOperation(value = "Individual EI job", notes = "")
253 @ApiResponse(code = 201, message = "Job created", response = VoidResponse.class), //
254 @ApiResponse(code = 200, message = "Job updated", response = VoidResponse.class), // ,
257 message = "Enrichment Information type is not found",
258 response = ErrorResponse.ErrorInfo.class)})
259 public Mono<ResponseEntity<Object>> putIndividualEiJob( //
260 @PathVariable("eiJobId") String eiJobId, //
261 @RequestBody ConsumerEiJobInfo eiJobObject) {
263 final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
265 return validatePutEiJob(eiJobId, eiJobObject) //
266 .flatMap(this::notifyProducersNewJob) //
267 .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
268 .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
269 .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
272 private Mono<EiJob> notifyProducersNewJob(EiJob newEiJob) {
273 return this.producerCallbacks.notifyProducersJobStarted(newEiJob) //
274 .flatMap(noOfAcceptingProducers -> {
275 if (noOfAcceptingProducers.intValue() > 0) {
276 return Mono.just(newEiJob);
278 return Mono.error(new ServiceException("Job not accepted by any producers", HttpStatus.CONFLICT));
283 private Mono<EiJob> validatePutEiJob(String eiJobId, ConsumerEiJobInfo eiJobInfo) {
285 EiType eiType = this.eiTypes.getType(eiJobInfo.eiTypeId);
286 validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobData);
287 EiJob existingEiJob = this.eiJobs.get(eiJobId);
289 if (existingEiJob != null && !existingEiJob.getTypeId().equals(eiJobInfo.eiTypeId)) {
290 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
292 return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
293 } catch (Exception e) {
294 return Mono.error(e);
298 private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
299 if (schemaObj != null) { // schema is optional for now
301 ObjectMapper mapper = new ObjectMapper();
303 String schemaAsString = mapper.writeValueAsString(schemaObj);
304 JSONObject schemaJSON = new JSONObject(schemaAsString);
305 Schema schema = SchemaLoader.load(schemaJSON);
307 String objectAsString = mapper.writeValueAsString(object);
308 JSONObject json = new JSONObject(objectAsString);
309 schema.validate(json);
310 } catch (Exception e) {
311 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
316 private EiJob toEiJob(ConsumerEiJobInfo info, String id, EiType type) {
317 return EiJob.builder() //
319 .typeId(type.getId()) //
320 .owner(info.owner) //
321 .jobData(info.jobData) //
322 .targetUrl(info.targetUri) //
323 .jobStatusUrl(info.statusNotificationUri == null ? "" : info.statusNotificationUri) //
327 private ConsumerEiTypeInfo toEiTypeInfo() {
328 return new ConsumerEiTypeInfo();
331 private ConsumerEiJobInfo toEiJobInfo(EiJob s) {
332 return new ConsumerEiJobInfo(s.getTypeId(), s.getJobData(), s.getOwner(), s.getTargetUrl(),
333 s.getJobStatusUrl());