2 * ========================LICENSE_START=================================
4 * ======================================================================
5 * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
6 * ======================================================================
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.RequestParam;
59 import org.springframework.web.bind.annotation.RestController;
60 import reactor.core.publisher.Mono;
62 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
63 @RestController("ConsumerController")
64 @Api(tags = {ConsumerConsts.CONSUMER_API_NAME})
65 public class ConsumerController {
68 ApplicationConfig applicationConfig;
71 private EiJobs eiJobs;
74 private EiTypes eiTypes;
77 ProducerCallbacks producerCallbacks;
79 private static Gson gson = new GsonBuilder() //
83 @GetMapping(path = ConsumerConsts.API_ROOT + "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
84 @ApiOperation(value = "EI type identifiers", notes = "")
89 message = "EI type identifiers",
90 response = String.class,
91 responseContainer = "List"), //
93 public ResponseEntity<Object> getEiTypeIdentifiers( //
95 List<String> result = new ArrayList<>();
96 for (EiType eiType : this.eiTypes.getAllEiTypes()) {
97 result.add(eiType.getId());
100 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
103 @GetMapping(path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
104 @ApiOperation(value = "Individual EI type", notes = "")
107 @ApiResponse(code = 200, message = "EI type", response = ConsumerEiTypeInfo.class), //
110 message = "Enrichment Information type is not found",
111 response = ErrorResponse.ErrorInfo.class)})
112 public ResponseEntity<Object> getEiType( //
113 @PathVariable("eiTypeId") String eiTypeId) {
115 EiType t = this.eiTypes.getType(eiTypeId);
116 ConsumerEiTypeInfo info = toEiTypeInfo(t);
117 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
118 } catch (Exception e) {
119 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
124 path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs",
125 produces = MediaType.APPLICATION_JSON_VALUE)
126 @ApiOperation(value = "EI job identifiers", notes = "")
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( //
139 @PathVariable("eiTypeId") String eiTypeId, //
141 name = ConsumerConsts.OWNER_PARAM,
143 value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
144 @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
146 this.eiTypes.getType(eiTypeId); // Just to check that the type exists
147 List<String> result = new ArrayList<>();
149 for (EiJob job : this.eiJobs.getJobsForOwner(owner)) {
150 if (eiTypeId == null || job.type().getId().equals(eiTypeId)) {
151 result.add(job.id());
155 for (EiJob job : this.eiJobs.getJobsForType(eiTypeId)) {
156 result.add(job.id());
159 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
160 } catch (Exception e) {
161 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
166 path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}",
167 produces = MediaType.APPLICATION_JSON_VALUE)
168 @ApiOperation(value = "Individual EI Job", notes = "")
171 @ApiResponse(code = 200, message = "EI Job", response = ConsumerEiJobInfo.class), //
174 message = "Enrichment Information type or job is not found",
175 response = ErrorResponse.ErrorInfo.class)})
176 public ResponseEntity<Object> getIndividualEiJob( //
177 @PathVariable("eiTypeId") String eiTypeId, //
178 @PathVariable("eiJobId") String eiJobId) {
180 this.eiTypes.getType(eiTypeId); // Just to check that the type exists
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);
189 path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}/status",
190 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 type or job is not found",
198 response = ErrorResponse.ErrorInfo.class)})
199 public ResponseEntity<Object> getEiJobStatus( //
200 @PathVariable("eiTypeId") String eiTypeId, //
201 @PathVariable("eiJobId") String eiJobId) {
203 this.eiTypes.getType(eiTypeId); // Just to check that the type exists
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 ConsumerEiJobStatus toEiJobStatus(EiJob job) {
213 return new ConsumerEiJobStatus(ConsumerEiJobStatus.OperationalState.ENABLED);
217 path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}",
218 produces = MediaType.APPLICATION_JSON_VALUE)
219 @ApiOperation(value = "Individual EI Job", notes = "")
222 @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
223 @ApiResponse(code = 204, message = "Job deleted", response = VoidResponse.class),
226 message = "Enrichment Information type or job is not found",
227 response = ErrorResponse.ErrorInfo.class)})
228 public ResponseEntity<Object> deleteIndividualEiJob( //
229 @PathVariable("eiTypeId") String eiTypeId, //
230 @PathVariable("eiJobId") String eiJobId) {
232 EiJob job = this.eiJobs.getJob(eiJobId);
233 this.eiJobs.remove(job);
234 this.producerCallbacks.notifyProducersJobDeleted(job);
235 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
236 } catch (Exception e) {
237 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
242 path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}", //
243 produces = MediaType.APPLICATION_JSON_VALUE, //
244 consumes = MediaType.APPLICATION_JSON_VALUE)
245 @ApiOperation(value = "Individual EI Job", notes = "")
248 @ApiResponse(code = 201, message = "Job created", response = VoidResponse.class), //
249 @ApiResponse(code = 200, message = "Job updated", response = VoidResponse.class), // ,
252 message = "Enrichment Information type is not found",
253 response = ErrorResponse.ErrorInfo.class)})
254 public Mono<ResponseEntity<Object>> putIndividualEiJob( //
255 @PathVariable("eiTypeId") String eiTypeId, //
256 @PathVariable("eiJobId") String eiJobId, //
257 @RequestBody ConsumerEiJobInfo eiJobInfo) {
259 final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
261 return validatePutEiJob(eiTypeId, eiJobId, eiJobInfo) //
262 .flatMap(this::notifyProducersNewJob) //
263 .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
264 .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
265 .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
268 private Mono<EiJob> notifyProducersNewJob(EiJob newEiJob) {
269 return this.producerCallbacks.notifyProducersJobStarted(newEiJob) //
270 .flatMap(noOfAcceptingProducers -> {
271 if (noOfAcceptingProducers.intValue() > 0) {
272 return Mono.just(newEiJob);
274 return Mono.error(new ServiceException("Job not accepted by any producers", HttpStatus.CONFLICT));
279 private Mono<EiJob> validatePutEiJob(String eiTypeId, String eiJobId, ConsumerEiJobInfo eiJobInfo) {
281 EiType eiType = this.eiTypes.getType(eiTypeId);
282 validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobData);
283 EiJob existingEiJob = this.eiJobs.get(eiJobId);
285 if (existingEiJob != null && !existingEiJob.type().getId().equals(eiTypeId)) {
286 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
288 return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
289 } catch (Exception e) {
290 return Mono.error(e);
294 private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
295 if (schemaObj != null) { // schema is optional for now
297 ObjectMapper mapper = new ObjectMapper();
299 String schemaAsString = mapper.writeValueAsString(schemaObj);
300 JSONObject schemaJSON = new JSONObject(schemaAsString);
301 Schema schema = SchemaLoader.load(schemaJSON);
303 String objectAsString = mapper.writeValueAsString(object);
304 JSONObject json = new JSONObject(objectAsString);
305 schema.validate(json);
306 } catch (Exception e) {
307 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
314 private EiJob toEiJob(ConsumerEiJobInfo info, String id, EiType type) {
315 return ImmutableEiJob.builder() //
318 .owner(info.owner) //
319 .jobData(info.jobData) //
320 .targetUri(info.targetUri) //
324 private ConsumerEiTypeInfo toEiTypeInfo(EiType t) {
325 return new ConsumerEiTypeInfo(t.getJobDataSchema());
328 private ConsumerEiJobInfo toEiJobInfo(EiJob s) {
329 return new ConsumerEiJobInfo(s.jobData(), s.owner(), s.targetUri());