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.a1e;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
27 import io.swagger.v3.oas.annotations.Operation;
28 import io.swagger.v3.oas.annotations.Parameter;
29 import io.swagger.v3.oas.annotations.media.ArraySchema;
30 import io.swagger.v3.oas.annotations.media.Content;
31 import io.swagger.v3.oas.annotations.media.Schema;
32 import io.swagger.v3.oas.annotations.responses.ApiResponse;
33 import io.swagger.v3.oas.annotations.responses.ApiResponses;
34 import io.swagger.v3.oas.annotations.tags.Tag;
36 import java.lang.invoke.MethodHandles;
37 import java.util.ArrayList;
38 import java.util.List;
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.r1producer.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.EiProducers;
49 import org.oransc.enrichment.repository.EiType;
50 import org.oransc.enrichment.repository.EiTypes;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.http.HttpStatus;
55 import org.springframework.http.MediaType;
56 import org.springframework.http.ResponseEntity;
57 import org.springframework.web.bind.annotation.DeleteMapping;
58 import org.springframework.web.bind.annotation.GetMapping;
59 import org.springframework.web.bind.annotation.PathVariable;
60 import org.springframework.web.bind.annotation.PutMapping;
61 import org.springframework.web.bind.annotation.RequestBody;
62 import org.springframework.web.bind.annotation.RequestMapping;
63 import org.springframework.web.bind.annotation.RequestParam;
64 import org.springframework.web.bind.annotation.RestController;
65 import reactor.core.publisher.Mono;
67 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
68 @RestController("A1-EI")
69 @Tag(name = A1eConsts.CONSUMER_API_NAME)
70 @RequestMapping(path = A1eConsts.API_ROOT, produces = MediaType.APPLICATION_JSON_VALUE)
71 public class A1eController {
73 private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
76 ApplicationConfig applicationConfig;
79 private EiJobs eiJobs;
82 private EiTypes eiTypes;
85 private EiProducers eiProducers;
88 ProducerCallbacks producerCallbacks;
90 private static Gson gson = new GsonBuilder().create();
92 @GetMapping(path = "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
93 @Operation(summary = "EI type identifiers", description = "")
98 description = "EI type identifiers", //
99 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))), //
101 public ResponseEntity<Object> getEiTypeIdentifiers( //
103 List<String> result = new ArrayList<>();
104 for (EiType eiType : this.eiTypes.getAllInfoTypes()) {
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 @Operation(summary = "Individual EI type", description = "")
116 responseCode = "200",
117 description = "EI type", //
118 content = @Content(schema = @Schema(implementation = A1eEiTypeInfo.class))), //
120 responseCode = "404",
121 description = "Enrichment Information type is not found", //
122 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
124 public ResponseEntity<Object> getEiType( //
125 @PathVariable("eiTypeId") String eiTypeId) {
127 this.eiTypes.getType(eiTypeId); // Make sure that the type exists
128 A1eEiTypeInfo info = toEiTypeInfo();
129 return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
130 } catch (Exception e) {
131 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
135 @GetMapping(path = "/eijobs", produces = MediaType.APPLICATION_JSON_VALUE)
136 @Operation(summary = "EI job identifiers", description = "query for EI job identifiers")
140 responseCode = "200",
141 description = "EI job identifiers", //
142 content = @Content(array = @ArraySchema(schema = @Schema(implementation = String.class)))),
144 responseCode = "404",
145 description = "Enrichment Information type is not found", //
146 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
148 public ResponseEntity<Object> getEiJobIds( //
150 name = A1eConsts.EI_TYPE_ID_PARAM,
152 description = A1eConsts.EI_TYPE_ID_PARAM_DESCRIPTION) //
153 @RequestParam(name = A1eConsts.EI_TYPE_ID_PARAM, required = false) String eiTypeId,
155 name = A1eConsts.OWNER_PARAM,
157 description = A1eConsts.OWNER_PARAM_DESCRIPTION) //
158 @RequestParam(name = A1eConsts.OWNER_PARAM, required = false) String owner) {
160 List<String> result = new ArrayList<>();
162 for (EiJob job : this.eiJobs.getJobsForOwner(owner)) {
163 if (eiTypeId == null || job.getTypeId().equals(eiTypeId)) {
164 result.add(job.getId());
167 } else if (eiTypeId != null) {
168 this.eiJobs.getJobsForType(eiTypeId).forEach(job -> result.add(job.getId()));
170 this.eiJobs.getJobs().forEach(job -> result.add(job.getId()));
172 return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
176 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
180 @GetMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE) //
181 @Operation(summary = "Individual EI job", description = "") //
185 responseCode = "200",
186 description = "EI job", //
187 content = @Content(schema = @Schema(implementation = A1eEiJobInfo.class))), //
189 responseCode = "404",
190 description = "Enrichment Information job is not found", //
191 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
193 public ResponseEntity<Object> getIndividualEiJob( //
194 @PathVariable("eiJobId") String eiJobId) {
196 EiJob job = this.eiJobs.getJob(eiJobId);
197 return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
198 } catch (Exception e) {
199 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
203 @GetMapping(path = "/eijobs/{eiJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
204 @Operation(summary = "EI job status", description = "")
208 responseCode = "200",
209 description = "EI job status", //
210 content = @Content(schema = @Schema(implementation = A1eEiJobStatus.class))), //
212 responseCode = "404",
213 description = "Enrichment Information job is not found", //
214 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
216 public ResponseEntity<Object> getEiJobStatus( //
217 @PathVariable("eiJobId") String eiJobId) {
219 EiJob job = this.eiJobs.getJob(eiJobId);
220 return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
221 } catch (Exception e) {
222 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
226 private A1eEiJobStatus toEiJobStatus(EiJob job) {
227 return this.eiProducers.isJobEnabled(job) ? new A1eEiJobStatus(A1eEiJobStatus.EiJobStatusValues.ENABLED)
228 : new A1eEiJobStatus(A1eEiJobStatus.EiJobStatusValues.DISABLED);
232 @DeleteMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
233 @Operation(summary = "Individual EI job", description = "")
237 responseCode = "200",
238 description = "Not used", //
239 content = @Content(schema = @Schema(implementation = VoidResponse.class))),
241 responseCode = "204",
242 description = "Job deleted", //
243 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
245 responseCode = "404",
246 description = "Enrichment Information job is not found", //
247 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
249 public ResponseEntity<Object> deleteIndividualEiJob( //
250 @PathVariable("eiJobId") String eiJobId) {
252 EiJob job = this.eiJobs.getJob(eiJobId);
253 this.eiJobs.remove(job, this.eiProducers);
254 return new ResponseEntity<>(HttpStatus.NO_CONTENT);
255 } catch (Exception e) {
256 return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
261 path = "/eijobs/{eiJobId}", //
262 produces = MediaType.APPLICATION_JSON_VALUE, //
263 consumes = MediaType.APPLICATION_JSON_VALUE)
264 @Operation(summary = "Individual EI job", description = "")
268 responseCode = "201",
269 description = "Job created", //
270 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
272 responseCode = "200",
273 description = "Job updated", //
274 content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
276 responseCode = "404",
277 description = "Enrichment Information type is not found", //
278 content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
280 public Mono<ResponseEntity<Object>> putIndividualEiJob( //
281 @PathVariable("eiJobId") String eiJobId, //
282 @RequestBody A1eEiJobInfo eiJobObject) {
284 final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
286 return validatePutEiJob(eiJobId, eiJobObject) //
287 .flatMap(this::startEiJob) //
288 .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
289 .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
290 .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
293 private Mono<EiJob> startEiJob(EiJob newEiJob) {
294 return this.producerCallbacks.startInfoSubscriptionJob(newEiJob, eiProducers) //
295 .doOnNext(noOfAcceptingProducers -> this.logger.debug(
296 "Started EI job {}, number of activated producers: {}", newEiJob.getId(), noOfAcceptingProducers)) //
297 .flatMap(noOfAcceptingProducers -> Mono.just(newEiJob));
300 private Mono<EiJob> validatePutEiJob(String eiJobId, A1eEiJobInfo eiJobInfo) {
302 EiType eiType = this.eiTypes.getType(eiJobInfo.eiTypeId);
303 validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobDefinition);
304 EiJob existingEiJob = this.eiJobs.get(eiJobId);
306 if (existingEiJob != null && !existingEiJob.getTypeId().equals(eiJobInfo.eiTypeId)) {
307 throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
309 return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
310 } catch (Exception e) {
311 return Mono.error(e);
315 private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
316 if (schemaObj != null) { // schema is optional for now
318 ObjectMapper mapper = new ObjectMapper();
320 String schemaAsString = mapper.writeValueAsString(schemaObj);
321 JSONObject schemaJSON = new JSONObject(schemaAsString);
322 org.everit.json.schema.Schema schema = org.everit.json.schema.loader.SchemaLoader.load(schemaJSON);
324 String objectAsString = mapper.writeValueAsString(object);
325 JSONObject json = new JSONObject(objectAsString);
326 schema.validate(json);
327 } catch (Exception e) {
328 throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
333 private EiJob toEiJob(A1eEiJobInfo info, String id, EiType type) {
334 return EiJob.builder() //
336 .typeId(type.getId()) //
337 .owner(info.owner) //
338 .jobData(info.jobDefinition) //
339 .targetUrl(info.jobResultUri) //
340 .jobStatusUrl(info.statusNotificationUri == null ? "" : info.statusNotificationUri) //
344 private A1eEiTypeInfo toEiTypeInfo() {
345 return new A1eEiTypeInfo();
348 private A1eEiJobInfo toEiJobInfo(EiJob s) {
349 return new A1eEiJobInfo(s.getTypeId(), s.getJobData(), s.getOwner(), s.getTargetUrl(), s.getJobStatusUrl());