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.lang.invoke.MethodHandles;
34 import java.util.ArrayList;
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.clients.ProducerCallbacks;
41 import org.oransc.enrichment.configuration.ApplicationConfig;
42 import org.oransc.enrichment.controllers.ErrorResponse;
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.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
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.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 public class ConsumerController {
68 private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
71 ApplicationConfig applicationConfig;
74 private EiJobs eiJobs;
77 private EiTypes eiTypes;
80 ProducerCallbacks producerCallbacks;
82 private static Gson gson = new GsonBuilder() //
86 @GetMapping(path = ConsumerConsts.API_ROOT + "/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 = ConsumerConsts.API_ROOT + "/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 EiType t = this.eiTypes.getType(eiTypeId);
119 ConsumerEiTypeInfo info = toEiTypeInfo(t);
120 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
121 } catch (Exception e) {
122 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
127 path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs",
128 produces = MediaType.APPLICATION_JSON_VALUE)
129 @ApiOperation(value = "EI job identifiers", notes = "")
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( //
142 @PathVariable("eiTypeId") String eiTypeId, //
144 name = ConsumerConsts.OWNER_PARAM,
146 value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
149 this.eiTypes.getType(eiTypeId); // Just to check that the type exists
150 List<String> result = new ArrayList<>();
151 for (EiJob job : this.eiJobs.getJobsForType(eiTypeId)) {
152 result.add(job.id());
154 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
155 } catch (Exception e) {
156 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
161 path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}",
162 produces = MediaType.APPLICATION_JSON_VALUE)
163 @ApiOperation(value = "Individual EI Job", notes = "")
166 @ApiResponse(code = 200, message = "EI Job", response = ConsumerEiJobInfo.class), //
169 message = "Enrichment Information type or job is not found",
170 response = ErrorResponse.ErrorInfo.class)})
171 public ResponseEntity<Object> getIndividualEiJob( //
172 @PathVariable("eiTypeId") String eiTypeId, //
173 @PathVariable("eiJobId") String eiJobId) {
175 this.eiTypes.getType(eiTypeId); // Just to check that the type exists
176 EiJob job = this.eiJobs.getJob(eiJobId);
177 return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
178 } catch (Exception e) {
179 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
184 path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}/status",
185 produces = MediaType.APPLICATION_JSON_VALUE)
186 @ApiOperation(value = "EI Job status", notes = "")
189 @ApiResponse(code = 200, message = "EI Job status", response = ConsumerEiJobStatus.class), //
192 message = "Enrichment Information type or job is not found",
193 response = ErrorResponse.ErrorInfo.class)})
194 public ResponseEntity<Object> getEiJobStatus( //
195 @PathVariable("eiTypeId") String eiTypeId, //
196 @PathVariable("eiJobId") String eiJobId) {
198 this.eiTypes.getType(eiTypeId); // Just to check that the type exists
199 EiJob job = this.eiJobs.getJob(eiJobId);
200 return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
201 } catch (Exception e) {
202 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
206 private ConsumerEiJobStatus toEiJobStatus(EiJob job) {
208 return new ConsumerEiJobStatus(ConsumerEiJobStatus.OperationalState.ENABLED);
212 path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}",
213 produces = MediaType.APPLICATION_JSON_VALUE)
214 @ApiOperation(value = "Individual EI Job", notes = "")
217 @ApiResponse(code = 200, message = "Not used", response = void.class),
218 @ApiResponse(code = 204, message = "Job deleted", response = void.class),
221 message = "Enrichment Information type or job is not found",
222 response = ErrorResponse.ErrorInfo.class)})
223 public ResponseEntity<Object> deleteIndividualEiJob( //
224 @PathVariable("eiTypeId") String eiTypeId, //
225 @PathVariable("eiJobId") String eiJobId) {
227 EiJob job = this.eiJobs.getJob(eiJobId);
228 this.eiJobs.remove(job);
229 this.producerCallbacks.notifyProducersJobDeleted(job);
230 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
231 } catch (Exception e) {
232 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
237 path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}", //
238 produces = MediaType.APPLICATION_JSON_VALUE, //
239 consumes = MediaType.APPLICATION_JSON_VALUE)
240 @ApiOperation(value = "Individual EI Job", notes = "")
243 @ApiResponse(code = 201, message = "Job created", response = void.class), //
244 @ApiResponse(code = 200, message = "Job updated", response = void.class), // ,
247 message = "Enrichment Information type is not found",
248 response = ErrorResponse.ErrorInfo.class)})
249 public Mono<ResponseEntity<Object>> putIndividualEiJob( //
250 @PathVariable("eiTypeId") String eiTypeId, //
251 @PathVariable("eiJobId") String eiJobId, //
252 @RequestBody ConsumerEiJobInfo eiJobInfo) {
254 final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
256 return validatePutEiJob(eiTypeId, eiJobId, eiJobInfo) //
257 .flatMap(this::notifyProducersNewJob) //
258 .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
259 .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
260 .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
263 private Mono<EiJob> notifyProducersNewJob(EiJob newEiJob) {
264 return this.producerCallbacks.notifyProducersJobStarted(newEiJob) //
265 .flatMap(noOfAcceptingProducers -> {
266 if (noOfAcceptingProducers.intValue() > 0) {
267 return Mono.just(newEiJob);
269 return Mono.error(new ServiceException("Job not accepted by any producers", HttpStatus.CONFLICT));
274 private Mono<EiJob> validatePutEiJob(String eiTypeId, String eiJobId, ConsumerEiJobInfo eiJobInfo) {
276 EiType eiType = this.eiTypes.getType(eiTypeId);
277 validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobData);
278 EiJob existingEiJob = this.eiJobs.get(eiJobId);
280 if (existingEiJob != null && !existingEiJob.type().getId().equals(eiTypeId)) {
281 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
283 return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
284 } catch (Exception e) {
285 return Mono.error(e);
289 private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
290 if (schemaObj != null) { // schema is optional for now
292 ObjectMapper mapper = new ObjectMapper();
294 String schemaAsString = mapper.writeValueAsString(schemaObj);
295 JSONObject schemaJSON = new JSONObject(schemaAsString);
296 Schema schema = SchemaLoader.load(schemaJSON);
298 String objectAsString = mapper.writeValueAsString(object);
299 JSONObject json = new JSONObject(objectAsString);
300 schema.validate(json);
301 } catch (Exception e) {
302 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
309 private EiJob toEiJob(ConsumerEiJobInfo info, String id, EiType type) {
310 return ImmutableEiJob.builder() //
313 .owner(info.owner) //
314 .jobData(info.jobData) //
315 .targetUri(info.targetUri) //
319 private ConsumerEiTypeInfo toEiTypeInfo(EiType t) {
320 return new ConsumerEiTypeInfo(t.getJobDataSchema());
323 private ConsumerEiJobInfo toEiJobInfo(EiJob s) {
324 return new ConsumerEiJobInfo(s.jobData(), s.owner(), s.targetUri());