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.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.configuration.ApplicationConfig;
41 import org.oransc.enrichment.controllers.ErrorResponse;
42 import org.oransc.enrichment.controllers.VoidResponse;
43 import org.oransc.enrichment.controllers.producer.ProducerCallbacks;
44 import org.oransc.enrichment.exceptions.ServiceException;
45 import org.oransc.enrichment.repository.EiJob;
46 import org.oransc.enrichment.repository.EiJobs;
47 import org.oransc.enrichment.repository.EiProducers;
48 import org.oransc.enrichment.repository.EiType;
49 import org.oransc.enrichment.repository.EiTypes;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
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 {
72 private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
75 ApplicationConfig applicationConfig;
78 private EiJobs eiJobs;
81 private EiTypes eiTypes;
84 private EiProducers eiProducers;
87 ProducerCallbacks producerCallbacks;
89 private static Gson gson = new GsonBuilder().create();
91 @GetMapping(path = "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
92 @ApiOperation(value = "EI type identifiers", notes = "")
97 message = "EI type identifiers",
98 response = String.class,
99 responseContainer = "List"), //
101 public ResponseEntity<Object> getEiTypeIdentifiers( //
103 List<String> result = new ArrayList<>();
104 for (EiType eiType : this.eiTypes.getAllEiTypes()) {
105 result.add(eiType.getId());
108 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
111 @GetMapping(path = "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
112 @ApiOperation(value = "Individual EI type", notes = "")
115 @ApiResponse(code = 200, message = "EI type", response = ConsumerEiTypeInfo.class), //
118 message = "Enrichment Information type is not found",
119 response = ErrorResponse.ErrorInfo.class)})
120 public ResponseEntity<Object> getEiType( //
121 @PathVariable("eiTypeId") String eiTypeId) {
123 this.eiTypes.getType(eiTypeId); // Make sure that the type exists
124 ConsumerEiTypeInfo info = toEiTypeInfo();
125 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
126 } catch (Exception e) {
127 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
131 @GetMapping(path = "/eijobs", produces = MediaType.APPLICATION_JSON_VALUE)
132 @ApiOperation(value = "EI job identifiers", notes = "query for EI job identifiers")
137 message = "EI job identifiers",
138 response = String.class,
139 responseContainer = "List"), //
142 message = "Enrichment Information type is not found",
143 response = ErrorResponse.ErrorInfo.class)})
144 public ResponseEntity<Object> getEiJobIds( //
146 name = ConsumerConsts.EI_TYPE_ID_PARAM,
148 value = ConsumerConsts.EI_TYPE_ID_PARAM_DESCRIPTION) //
149 @RequestParam(name = ConsumerConsts.EI_TYPE_ID_PARAM, required = false) String eiTypeId,
151 name = ConsumerConsts.OWNER_PARAM,
153 value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
154 @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
156 List<String> result = new ArrayList<>();
158 for (EiJob job : this.eiJobs.getJobsForOwner(owner)) {
159 if (eiTypeId == null || job.getTypeId().equals(eiTypeId)) {
160 result.add(job.getId());
163 } else if (eiTypeId != null) {
164 this.eiJobs.getJobsForType(eiTypeId).forEach(job -> result.add(job.getId()));
166 this.eiJobs.getJobs().forEach(job -> result.add(job.getId()));
168 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
172 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
176 @GetMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
177 @ApiOperation(value = "Individual EI job", notes = "")
180 @ApiResponse(code = 200, message = "EI job", response = ConsumerEiJobInfo.class), //
183 message = "Enrichment Information job is not found",
184 response = ErrorResponse.ErrorInfo.class)})
185 public ResponseEntity<Object> getIndividualEiJob( //
186 @PathVariable("eiJobId") String eiJobId) {
188 EiJob job = this.eiJobs.getJob(eiJobId);
189 return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
190 } catch (Exception e) {
191 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
195 @GetMapping(path = "/eijobs/{eiJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
196 @ApiOperation(value = "EI job status", notes = "")
199 @ApiResponse(code = 200, message = "EI job status", response = ConsumerEiJobStatus.class), //
202 message = "Enrichment Information job is not found",
203 response = ErrorResponse.ErrorInfo.class)})
204 public ResponseEntity<Object> getEiJobStatus( //
205 @PathVariable("eiJobId") String eiJobId) {
207 EiJob job = this.eiJobs.getJob(eiJobId);
208 return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
209 } catch (Exception e) {
210 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
214 private ConsumerEiJobStatus toEiJobStatus(EiJob job) {
215 return this.eiProducers.isJobEnabled(job)
216 ? new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.ENABLED)
217 : new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.DISABLED);
221 @DeleteMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
222 @ApiOperation(value = "Individual EI job", notes = "")
225 @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
226 @ApiResponse(code = 204, message = "Job deleted", response = VoidResponse.class),
229 message = "Enrichment Information job is not found",
230 response = ErrorResponse.ErrorInfo.class)})
231 public ResponseEntity<Object> deleteIndividualEiJob( //
232 @PathVariable("eiJobId") String eiJobId) {
234 EiJob job = this.eiJobs.getJob(eiJobId);
235 this.eiJobs.remove(job, this.eiProducers);
236 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
237 } catch (Exception e) {
238 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
243 path = "/eijobs/{eiJobId}", //
244 produces = MediaType.APPLICATION_JSON_VALUE, //
245 consumes = MediaType.APPLICATION_JSON_VALUE)
246 @ApiOperation(value = "Individual EI job", notes = "")
249 @ApiResponse(code = 201, message = "Job created", response = VoidResponse.class), //
250 @ApiResponse(code = 200, message = "Job updated", response = VoidResponse.class), // ,
253 message = "Enrichment Information type is not found",
254 response = ErrorResponse.ErrorInfo.class)})
255 public Mono<ResponseEntity<Object>> putIndividualEiJob( //
256 @PathVariable("eiJobId") String eiJobId, //
257 @RequestBody ConsumerEiJobInfo eiJobObject) {
259 final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
261 return validatePutEiJob(eiJobId, eiJobObject) //
262 .flatMap(this::startEiJob) //
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> startEiJob(EiJob newEiJob) {
269 return this.producerCallbacks.startEiJob(newEiJob, eiProducers) //
270 .doOnNext(noOfAcceptingProducers -> this.logger.debug(
271 "Started EI job {}, number of activated producers: {}", newEiJob.getId(), noOfAcceptingProducers)) //
272 .flatMap(noOfAcceptingProducers -> Mono.just(newEiJob));
275 private Mono<EiJob> validatePutEiJob(String eiJobId, ConsumerEiJobInfo eiJobInfo) {
277 EiType eiType = this.eiTypes.getType(eiJobInfo.eiTypeId);
278 validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobData);
279 EiJob existingEiJob = this.eiJobs.get(eiJobId);
281 if (existingEiJob != null && !existingEiJob.getTypeId().equals(eiJobInfo.eiTypeId)) {
282 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
284 return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
285 } catch (Exception e) {
286 return Mono.error(e);
290 private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
291 if (schemaObj != null) { // schema is optional for now
293 ObjectMapper mapper = new ObjectMapper();
295 String schemaAsString = mapper.writeValueAsString(schemaObj);
296 JSONObject schemaJSON = new JSONObject(schemaAsString);
297 Schema schema = SchemaLoader.load(schemaJSON);
299 String objectAsString = mapper.writeValueAsString(object);
300 JSONObject json = new JSONObject(objectAsString);
301 schema.validate(json);
302 } catch (Exception e) {
303 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
308 private EiJob toEiJob(ConsumerEiJobInfo info, String id, EiType type) {
309 return EiJob.builder() //
311 .typeId(type.getId()) //
312 .owner(info.owner) //
313 .jobData(info.jobData) //
314 .targetUrl(info.targetUri) //
315 .jobStatusUrl(info.statusNotificationUri == null ? "" : info.statusNotificationUri) //
319 private ConsumerEiTypeInfo toEiTypeInfo() {
320 return new ConsumerEiTypeInfo();
323 private ConsumerEiJobInfo toEiJobInfo(EiJob s) {
324 return new ConsumerEiJobInfo(s.getTypeId(), s.getJobData(), s.getOwner(), s.getTargetUrl(),
325 s.getJobStatusUrl());