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.List;
36 import org.everit.json.schema.Schema;
37 import org.everit.json.schema.loader.SchemaLoader;
38 import org.json.JSONObject;
39 import org.oransc.enrichment.clients.ProducerCallbacks;
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.exceptions.ServiceException;
44 import org.oransc.enrichment.repository.EiJob;
45 import org.oransc.enrichment.repository.EiJobs;
46 import org.oransc.enrichment.repository.EiType;
47 import org.oransc.enrichment.repository.EiTypes;
48 import org.oransc.enrichment.repository.ImmutableEiJob;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.http.HttpStatus;
51 import org.springframework.http.MediaType;
52 import org.springframework.http.ResponseEntity;
53 import org.springframework.web.bind.annotation.DeleteMapping;
54 import org.springframework.web.bind.annotation.GetMapping;
55 import org.springframework.web.bind.annotation.PathVariable;
56 import org.springframework.web.bind.annotation.PutMapping;
57 import org.springframework.web.bind.annotation.RequestBody;
58 import org.springframework.web.bind.annotation.RequestMapping;
59 import org.springframework.web.bind.annotation.RequestParam;
60 import org.springframework.web.bind.annotation.RestController;
61 import reactor.core.publisher.Mono;
63 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
64 @RestController("ConsumerController")
65 @Api(tags = {ConsumerConsts.CONSUMER_API_NAME})
66 @RequestMapping(path = ConsumerConsts.API_ROOT, produces = MediaType.APPLICATION_JSON_VALUE)
67 public class ConsumerController {
70 ApplicationConfig applicationConfig;
73 private EiJobs eiJobs;
76 private EiTypes eiTypes;
79 ProducerCallbacks producerCallbacks;
81 private static Gson gson = new GsonBuilder() //
84 @GetMapping(path = "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
85 @ApiOperation(value = "EI type identifiers", notes = "")
90 message = "EI type identifiers",
91 response = String.class,
92 responseContainer = "List"), //
94 public ResponseEntity<Object> getEiTypeIdentifiers( //
96 List<String> result = new ArrayList<>();
97 for (EiType eiType : this.eiTypes.getAllEiTypes()) {
98 result.add(eiType.getId());
101 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
104 @GetMapping(path = "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
105 @ApiOperation(value = "Individual EI type", notes = "")
108 @ApiResponse(code = 200, message = "EI type", response = ConsumerEiTypeInfo.class), //
111 message = "Enrichment Information type is not found",
112 response = ErrorResponse.ErrorInfo.class)})
113 public ResponseEntity<Object> getEiType( //
114 @PathVariable("eiTypeId") String eiTypeId) {
116 this.eiTypes.getType(eiTypeId); // Make sure that the type exists
117 ConsumerEiTypeInfo info = toEiTypeInfo();
118 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
119 } catch (Exception e) {
120 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
124 @GetMapping(path = "/eijobs", produces = MediaType.APPLICATION_JSON_VALUE)
125 @ApiOperation(value = "EI job identifiers", notes = "query for EI job identifiers")
130 message = "EI job identifiers",
131 response = String.class,
132 responseContainer = "List"), //
135 message = "Enrichment Information type is not found",
136 response = ErrorResponse.ErrorInfo.class)})
137 public ResponseEntity<Object> getEiJobIds( //
139 name = ConsumerConsts.EI_TYPE_ID_PARAM,
141 value = ConsumerConsts.EI_TYPE_ID_PARAM_DESCRIPTION) //
142 @RequestParam(name = ConsumerConsts.EI_TYPE_ID_PARAM, required = false) String eiTypeId,
144 name = ConsumerConsts.OWNER_PARAM,
146 value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
147 @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
149 List<String> result = new ArrayList<>();
151 for (EiJob job : this.eiJobs.getJobsForOwner(owner)) {
152 if (eiTypeId == null || job.type().getId().equals(eiTypeId)) {
153 result.add(job.id());
156 } else if (eiTypeId != null) {
157 this.eiJobs.getJobsForType(eiTypeId).forEach(job -> result.add(job.id()));
159 this.eiJobs.getJobs().forEach(job -> result.add(job.id()));
161 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
165 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
169 @GetMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
170 @ApiOperation(value = "Individual EI job", notes = "")
173 @ApiResponse(code = 200, message = "EI job", response = ConsumerEiJobInfo.class), //
176 message = "Enrichment Information job is not found",
177 response = ErrorResponse.ErrorInfo.class)})
178 public ResponseEntity<Object> getIndividualEiJob( //
179 @PathVariable("eiJobId") String eiJobId) {
181 EiJob job = this.eiJobs.getJob(eiJobId);
182 return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
183 } catch (Exception e) {
184 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
188 @GetMapping(path = "/eijobs/{eiJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
189 @ApiOperation(value = "EI job status", notes = "")
192 @ApiResponse(code = 200, message = "EI job status", response = ConsumerEiJobStatus.class), //
195 message = "Enrichment Information job is not found",
196 response = ErrorResponse.ErrorInfo.class)})
197 public ResponseEntity<Object> getEiJobStatus( //
198 @PathVariable("eiJobId") String eiJobId) {
200 EiJob job = this.eiJobs.getJob(eiJobId);
201 return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
202 } catch (Exception e) {
203 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
207 private ConsumerEiJobStatus toEiJobStatus(EiJob job) {
209 return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.ENABLED);
212 @DeleteMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
213 @ApiOperation(value = "Individual EI job", notes = "")
216 @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
217 @ApiResponse(code = 204, message = "Job deleted", response = VoidResponse.class),
220 message = "Enrichment Information job is not found",
221 response = ErrorResponse.ErrorInfo.class)})
222 public ResponseEntity<Object> deleteIndividualEiJob( //
223 @PathVariable("eiJobId") String eiJobId) {
225 EiJob job = this.eiJobs.getJob(eiJobId);
226 this.eiJobs.remove(job);
227 this.producerCallbacks.notifyProducersJobDeleted(job);
228 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
229 } catch (Exception e) {
230 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
235 path = "/eijobs/{eiJobId}", //
236 produces = MediaType.APPLICATION_JSON_VALUE, //
237 consumes = MediaType.APPLICATION_JSON_VALUE)
238 @ApiOperation(value = "Individual EI job", notes = "")
241 @ApiResponse(code = 201, message = "Job created", response = VoidResponse.class), //
242 @ApiResponse(code = 200, message = "Job updated", response = VoidResponse.class), // ,
245 message = "Enrichment Information type is not found",
246 response = ErrorResponse.ErrorInfo.class)})
247 public Mono<ResponseEntity<Object>> putIndividualEiJob( //
248 @PathVariable("eiJobId") String eiJobId, //
249 @RequestBody ConsumerEiJobInfo eiJobObject) {
251 final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
253 return validatePutEiJob(eiJobId, eiJobObject) //
254 .flatMap(this::notifyProducersNewJob) //
255 .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
256 .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
257 .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
260 private Mono<EiJob> notifyProducersNewJob(EiJob newEiJob) {
261 return this.producerCallbacks.notifyProducersJobStarted(newEiJob) //
262 .flatMap(noOfAcceptingProducers -> {
263 if (noOfAcceptingProducers.intValue() > 0) {
264 return Mono.just(newEiJob);
266 return Mono.error(new ServiceException("Job not accepted by any producers", HttpStatus.CONFLICT));
271 private Mono<EiJob> validatePutEiJob(String eiJobId, ConsumerEiJobInfo eiJobInfo) {
273 EiType eiType = this.eiTypes.getType(eiJobInfo.eiTypeId);
274 validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobData);
275 EiJob existingEiJob = this.eiJobs.get(eiJobId);
277 if (existingEiJob != null && !existingEiJob.type().getId().equals(eiJobInfo.eiTypeId)) {
278 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
280 return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
281 } catch (Exception e) {
282 return Mono.error(e);
286 private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
287 if (schemaObj != null) { // schema is optional for now
289 ObjectMapper mapper = new ObjectMapper();
291 String schemaAsString = mapper.writeValueAsString(schemaObj);
292 JSONObject schemaJSON = new JSONObject(schemaAsString);
293 Schema schema = SchemaLoader.load(schemaJSON);
295 String objectAsString = mapper.writeValueAsString(object);
296 JSONObject json = new JSONObject(objectAsString);
297 schema.validate(json);
298 } catch (Exception e) {
299 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
306 private EiJob toEiJob(ConsumerEiJobInfo info, String id, EiType type) {
307 return ImmutableEiJob.builder() //
310 .owner(info.owner) //
311 .jobData(info.jobData) //
312 .targetUri(info.targetUri) //
316 private ConsumerEiTypeInfo toEiTypeInfo() {
317 return new ConsumerEiTypeInfo();
320 private ConsumerEiJobInfo toEiJobInfo(EiJob s) {
321 return new ConsumerEiJobInfo(s.type().getId(), s.jobData(), s.owner(), s.targetUri());