New EI Consumer API, aligned to ORAN WG2
[nonrtric.git] / enrichment-coordinator-service / src / main / java / org / oransc / enrichment / controllers / consumer / ConsumerController.java
index c43a495..bead826 100644 (file)
@@ -1,9 +1,9 @@
 /*-
  * ========================LICENSE_START=================================
- * ONAP : ccsdk oran
- * ======================================================================
- * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
- * ======================================================================
+ * O-RAN-SC
+ * %%
+ * Copyright (C) 2020 Nordix Foundation
+ * %%
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
@@ -20,9 +20,9 @@
 
 package org.oransc.enrichment.controllers.consumer;
 
+import com.fasterxml.jackson.databind.ObjectMapper;
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
-import com.google.gson.JsonObject;
 
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
@@ -30,20 +30,22 @@ import io.swagger.annotations.ApiParam;
 import io.swagger.annotations.ApiResponse;
 import io.swagger.annotations.ApiResponses;
 
-import java.lang.invoke.MethodHandles;
 import java.util.ArrayList;
 import java.util.List;
 
+import org.everit.json.schema.Schema;
+import org.everit.json.schema.loader.SchemaLoader;
+import org.json.JSONObject;
 import org.oransc.enrichment.clients.ProducerCallbacks;
 import org.oransc.enrichment.configuration.ApplicationConfig;
 import org.oransc.enrichment.controllers.ErrorResponse;
+import org.oransc.enrichment.controllers.VoidResponse;
+import org.oransc.enrichment.exceptions.ServiceException;
 import org.oransc.enrichment.repository.EiJob;
 import org.oransc.enrichment.repository.EiJobs;
 import org.oransc.enrichment.repository.EiType;
 import org.oransc.enrichment.repository.EiTypes;
 import org.oransc.enrichment.repository.ImmutableEiJob;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.MediaType;
@@ -53,15 +55,17 @@ import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.PutMapping;
 import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.RestController;
+import reactor.core.publisher.Mono;
 
 @SuppressWarnings("java:S3457") // No need to call "toString()" method as formatting and string ..
 @RestController("ConsumerController")
 @Api(tags = {ConsumerConsts.CONSUMER_API_NAME})
+@RequestMapping(path = ConsumerConsts.API_ROOT, produces = MediaType.APPLICATION_JSON_VALUE)
 public class ConsumerController {
 
-    private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
-
     @Autowired
     ApplicationConfig applicationConfig;
 
@@ -75,11 +79,10 @@ public class ConsumerController {
     ProducerCallbacks producerCallbacks;
 
     private static Gson gson = new GsonBuilder() //
-        .serializeNulls() //
         .create(); //
 
-    @GetMapping(path = ConsumerConsts.API_ROOT + "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
-    @ApiOperation(value = "Query EI type identifiers", notes = "DETAILS TBD")
+    @GetMapping(path = "/eitypes", produces = MediaType.APPLICATION_JSON_VALUE)
+    @ApiOperation(value = "EI type identifiers", notes = "")
     @ApiResponses(
         value = { //
             @ApiResponse(
@@ -98,8 +101,8 @@ public class ConsumerController {
         return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
     }
 
-    @GetMapping(path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
-    @ApiOperation(value = "Definitions for an individual EI Type", notes = "Query EI type")
+    @GetMapping(path = "/eitypes/{eiTypeId}", produces = MediaType.APPLICATION_JSON_VALUE)
+    @ApiOperation(value = "Individual EI type", notes = "")
     @ApiResponses(
         value = { //
             @ApiResponse(code = 200, message = "EI type", response = ConsumerEiTypeInfo.class), //
@@ -110,18 +113,16 @@ public class ConsumerController {
     public ResponseEntity<Object> getEiType( //
         @PathVariable("eiTypeId") String eiTypeId) {
         try {
-            EiType t = this.eiTypes.getType(eiTypeId);
-            ConsumerEiTypeInfo info = toEiTypeInfo(t);
+            this.eiTypes.getType(eiTypeId); // Make sure that the type exists
+            ConsumerEiTypeInfo info = toEiTypeInfo();
             return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
         } catch (Exception e) {
             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
         }
     }
 
-    @GetMapping(
-        path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs",
-        produces = MediaType.APPLICATION_JSON_VALUE)
-    @ApiOperation(value = "Query EI job identifiers", notes = "Returns the EI Job identifiers for an EI Type")
+    @GetMapping(path = "/eijobs", produces = MediaType.APPLICATION_JSON_VALUE)
+    @ApiOperation(value = "EI job identifiers", notes = "query for EI job identifiers")
     @ApiResponses(
         value = { //
             @ApiResponse(
@@ -134,40 +135,49 @@ public class ConsumerController {
                 message = "Enrichment Information type is not found",
                 response = ErrorResponse.ErrorInfo.class)})
     public ResponseEntity<Object> getEiJobIds( //
-        @PathVariable("eiTypeId") String eiTypeId, //
+        @ApiParam(
+            name = ConsumerConsts.EI_TYPE_ID_PARAM,
+            required = false, //
+            value = ConsumerConsts.EI_TYPE_ID_PARAM_DESCRIPTION) //
+        @RequestParam(name = ConsumerConsts.EI_TYPE_ID_PARAM, required = false) String eiTypeId,
         @ApiParam(
             name = ConsumerConsts.OWNER_PARAM,
             required = false, //
             value = ConsumerConsts.OWNER_PARAM_DESCRIPTION) //
-        String owner) {
+        @RequestParam(name = ConsumerConsts.OWNER_PARAM, required = false) String owner) {
         try {
-            this.eiTypes.getType(eiTypeId); // Just to check that the type exists
             List<String> result = new ArrayList<>();
-            for (EiJob job : this.eiJobs.getJobsForType(eiTypeId)) {
-                result.add(job.id());
+            if (owner != null) {
+                for (EiJob job : this.eiJobs.getJobsForOwner(owner)) {
+                    if (eiTypeId == null || job.type().getId().equals(eiTypeId)) {
+                        result.add(job.id());
+                    }
+                }
+            } else if (eiTypeId != null) {
+                this.eiJobs.getJobsForType(eiTypeId).forEach(job -> result.add(job.id()));
+            } else {
+                this.eiJobs.getJobs().forEach(job -> result.add(job.id()));
             }
             return new ResponseEntity<>(gson.toJson(result), HttpStatus.OK);
-        } catch (Exception e) {
+        } catch (
+
+        Exception e) {
             return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
         }
     }
 
-    @GetMapping(
-        path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}",
-        produces = MediaType.APPLICATION_JSON_VALUE)
-    @ApiOperation(value = "Individual EI Job", notes = "")
+    @GetMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
+    @ApiOperation(value = "Individual EI job", notes = "")
     @ApiResponses(
         value = { //
-            @ApiResponse(code = 200, message = "EI Job", response = ConsumerEiJobInfo.class), //
+            @ApiResponse(code = 200, message = "EI job", response = ConsumerEiJobInfo.class), //
             @ApiResponse(
                 code = 404,
-                message = "Enrichment Information type or job is not found",
+                message = "Enrichment Information job is not found",
                 response = ErrorResponse.ErrorInfo.class)})
     public ResponseEntity<Object> getIndividualEiJob( //
-        @PathVariable("eiTypeId") String eiTypeId, //
         @PathVariable("eiJobId") String eiJobId) {
         try {
-            this.eiTypes.getType(eiTypeId); // Just to check that the type exists
             EiJob job = this.eiJobs.getJob(eiJobId);
             return new ResponseEntity<>(gson.toJson(toEiJobInfo(job)), HttpStatus.OK);
         } catch (Exception e) {
@@ -175,22 +185,18 @@ public class ConsumerController {
         }
     }
 
-    @GetMapping(
-        path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}/status",
-        produces = MediaType.APPLICATION_JSON_VALUE)
-    @ApiOperation(value = "EI Job status", notes = "")
+    @GetMapping(path = "/eijobs/{eiJobId}/status", produces = MediaType.APPLICATION_JSON_VALUE)
+    @ApiOperation(value = "EI job status", notes = "")
     @ApiResponses(
         value = { //
-            @ApiResponse(code = 200, message = "EI Job status", response = ConsumerEiJobStatus.class), //
+            @ApiResponse(code = 200, message = "EI job status", response = ConsumerEiJobStatus.class), //
             @ApiResponse(
                 code = 404,
-                message = "Enrichment Information type or job is not found",
+                message = "Enrichment Information job is not found",
                 response = ErrorResponse.ErrorInfo.class)})
     public ResponseEntity<Object> getEiJobStatus( //
-        @PathVariable("eiTypeId") String eiTypeId, //
         @PathVariable("eiJobId") String eiJobId) {
         try {
-            this.eiTypes.getType(eiTypeId); // Just to check that the type exists
             EiJob job = this.eiJobs.getJob(eiJobId);
             return new ResponseEntity<>(gson.toJson(toEiJobStatus(job)), HttpStatus.OK);
         } catch (Exception e) {
@@ -200,23 +206,20 @@ public class ConsumerController {
 
     private ConsumerEiJobStatus toEiJobStatus(EiJob job) {
         // TODO
-        return new ConsumerEiJobStatus(ConsumerEiJobStatus.OperationalState.ENABLED);
+        return new ConsumerEiJobStatus(ConsumerEiJobStatus.EiJobStatusValues.ENABLED);
     }
 
-    @DeleteMapping(
-        path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}",
-        produces = MediaType.APPLICATION_JSON_VALUE)
-    @ApiOperation(value = "Individual EI Job", notes = "Delete EI job")
+    @DeleteMapping(path = "/eijobs/{eiJobId}", produces = MediaType.APPLICATION_JSON_VALUE)
+    @ApiOperation(value = "Individual EI job", notes = "")
     @ApiResponses(
         value = { //
-            @ApiResponse(code = 200, message = "Not used", response = void.class),
-            @ApiResponse(code = 204, message = "Job deleted", response = void.class),
+            @ApiResponse(code = 200, message = "Not used", response = VoidResponse.class),
+            @ApiResponse(code = 204, message = "Job deleted", response = VoidResponse.class),
             @ApiResponse(
                 code = 404,
-                message = "Enrichment Information type or job is not found",
+                message = "Enrichment Information job is not found",
                 response = ErrorResponse.ErrorInfo.class)})
     public ResponseEntity<Object> deleteIndividualEiJob( //
-        @PathVariable("eiTypeId") String eiTypeId, //
         @PathVariable("eiJobId") String eiJobId) {
         try {
             EiJob job = this.eiJobs.getJob(eiJobId);
@@ -229,39 +232,72 @@ public class ConsumerController {
     }
 
     @PutMapping(
-        path = ConsumerConsts.API_ROOT + "/eitypes/{eiTypeId}/eijobs/{eiJobId}", //
+        path = "/eijobs/{eiJobId}", //
         produces = MediaType.APPLICATION_JSON_VALUE, //
         consumes = MediaType.APPLICATION_JSON_VALUE)
-    @ApiOperation(value = "Individual EI Job", notes = "Create or update an EI Job")
+    @ApiOperation(value = "Individual EI job", notes = "")
     @ApiResponses(
         value = { //
-            @ApiResponse(code = 201, message = "Job created", response = void.class), //
-            @ApiResponse(code = 200, message = "Job updated", response = void.class), // ,
+            @ApiResponse(code = 201, message = "Job created", response = VoidResponse.class), //
+            @ApiResponse(code = 200, message = "Job updated", response = VoidResponse.class), // ,
             @ApiResponse(
                 code = 404,
                 message = "Enrichment Information type is not found",
                 response = ErrorResponse.ErrorInfo.class)})
-    public ResponseEntity<Object> putIndividualEiJob( //
-        @PathVariable("eiTypeId") String eiTypeId, //
+    public Mono<ResponseEntity<Object>> putIndividualEiJob( //
         @PathVariable("eiJobId") String eiJobId, //
-        @RequestBody ConsumerEiJobInfo eiJobInfo) {
+        @RequestBody ConsumerEiJobInfo eiJobObject) {
+
+        final boolean isNewJob = this.eiJobs.get(eiJobId) == null;
+
+        return validatePutEiJob(eiJobId, eiJobObject) //
+            .flatMap(this::notifyProducersNewJob) //
+            .doOnNext(newEiJob -> this.eiJobs.put(newEiJob)) //
+            .flatMap(newEiJob -> Mono.just(new ResponseEntity<>(isNewJob ? HttpStatus.CREATED : HttpStatus.OK)))
+            .onErrorResume(throwable -> Mono.just(ErrorResponse.create(throwable, HttpStatus.NOT_FOUND)));
+    }
+
+    private Mono<EiJob> notifyProducersNewJob(EiJob newEiJob) {
+        return this.producerCallbacks.notifyProducersJobStarted(newEiJob) //
+            .flatMap(noOfAcceptingProducers -> {
+                if (noOfAcceptingProducers.intValue() > 0) {
+                    return Mono.just(newEiJob);
+                } else {
+                    return Mono.error(new ServiceException("Job not accepted by any producers", HttpStatus.CONFLICT));
+                }
+            });
+    }
+
+    private Mono<EiJob> validatePutEiJob(String eiJobId, ConsumerEiJobInfo eiJobInfo) {
         try {
-            EiType eiType = this.eiTypes.getType(eiTypeId);
-            validateJobData(eiType.getJobDataSchema(), eiJobInfo.jobData);
-            final boolean newJob = this.eiJobs.get(eiJobId) == null;
-            EiJob eiJob = toEiJob(eiJobInfo, eiJobId, eiType);
-            this.eiJobs.put(eiJob);
-            this.producerCallbacks.notifyProducersJobCreated(eiJob);
-            return new ResponseEntity<>(newJob ? HttpStatus.CREATED : HttpStatus.OK);
+            EiType eiType = this.eiTypes.getType(eiJobInfo.eiTypeId);
+            validateJsonObjectAgainstSchema(eiType.getJobDataSchema(), eiJobInfo.jobData);
+            EiJob existingEiJob = this.eiJobs.get(eiJobId);
+
+            if (existingEiJob != null && !existingEiJob.type().getId().equals(eiJobInfo.eiTypeId)) {
+                throw new ServiceException("Not allowed to change type for existing EI job", HttpStatus.CONFLICT);
+            }
+            return Mono.just(toEiJob(eiJobInfo, eiJobId, eiType));
         } catch (Exception e) {
-            return ErrorResponse.create(e, HttpStatus.NOT_FOUND);
+            return Mono.error(e);
         }
     }
 
-    private void validateJobData(Object schemaObj, Object json) {
-        if (schemaObj instanceof JsonObject) {
-            JsonObject schema = (JsonObject) schemaObj;
-            logger.debug("schema {} json {}", schema, json);
+    private void validateJsonObjectAgainstSchema(Object schemaObj, Object object) throws ServiceException {
+        if (schemaObj != null) { // schema is optional for now
+            try {
+                ObjectMapper mapper = new ObjectMapper();
+
+                String schemaAsString = mapper.writeValueAsString(schemaObj);
+                JSONObject schemaJSON = new JSONObject(schemaAsString);
+                Schema schema = SchemaLoader.load(schemaJSON);
+
+                String objectAsString = mapper.writeValueAsString(object);
+                JSONObject json = new JSONObject(objectAsString);
+                schema.validate(json);
+            } catch (Exception e) {
+                throw new ServiceException("Json validation failure " + e.toString(), HttpStatus.CONFLICT);
+            }
         }
     }
 
@@ -273,14 +309,15 @@ public class ConsumerController {
             .type(type) //
             .owner(info.owner) //
             .jobData(info.jobData) //
+            .targetUri(info.targetUri) //
             .build();
     }
 
-    private ConsumerEiTypeInfo toEiTypeInfo(EiType t) {
-        return new ConsumerEiTypeInfo(t.getJobDataSchema());
+    private ConsumerEiTypeInfo toEiTypeInfo() {
+        return new ConsumerEiTypeInfo();
     }
 
     private ConsumerEiJobInfo toEiJobInfo(EiJob s) {
-        return new ConsumerEiJobInfo(s.jobData(), s.owner());
+        return new ConsumerEiJobInfo(s.type().getId(), s.jobData(), s.owner(), s.targetUri());
     }
 }