Added GET policy_ids in the agent NBI

Change-Id: I474982d9b2052f23a69247afaceb4772972057ab
Issue-ID: NONRTRIC-155
Signed-off-by: PatrikBuhr <patrik.buhr@est.tech>
diff --git a/policy-agent/docs/api.yaml b/policy-agent/docs/api.yaml
index a2f1b57..1696dad 100644
--- a/policy-agent/docs/api.yaml
+++ b/policy-agent/docs/api.yaml
@@ -425,7 +425,7 @@
         - name: type
           in: query
           description: type
-          required: true
+          required: false
           type: string
       responses:
         '200':
@@ -444,10 +444,6 @@
           description: RIC or policy type is not found
           schema:
             type: string
-        '405':
-          description: Change is not allowed
-          schema:
-            type: string
         '423':
           description: RIC is locked
           schema:
@@ -488,6 +484,46 @@
           schema:
             type: string
       deprecated: false
+  /policy_ids:
+    get:
+      tags:
+        - A1 Policy Management
+      summary: 'Query policies, only IDs returned'
+      operationId: getPolicyIdsUsingGET
+      produces:
+        - '*/*'
+      parameters:
+        - name: ric
+          in: query
+          description: ric
+          required: false
+          type: string
+        - name: service
+          in: query
+          description: service
+          required: false
+          type: string
+        - name: type
+          in: query
+          description: type
+          required: false
+          type: string
+      responses:
+        '200':
+          description: Policy ids
+          schema:
+            type: array
+            items:
+              type: string
+        '401':
+          description: Unauthorized
+        '403':
+          description: Forbidden
+        '404':
+          description: RIC or type not found
+          schema:
+            type: string
+      deprecated: false
   /policy_schema:
     get:
       tags:
@@ -762,7 +798,7 @@
     post:
       tags:
         - Service registry and supervision
-      summary: Keep the policies alive for a service
+      summary: Heartbeat from a serice
       operationId: keepAliveServiceUsingPOST
       consumes:
         - application/json
@@ -776,7 +812,7 @@
           type: string
       responses:
         '200':
-          description: Policies timeout supervision refreshed
+          description: 'Service supervision timer refreshed, OK'
           schema:
             type: string
         '201':
@@ -878,7 +914,7 @@
       keepAliveIntervalSeconds:
         type: integer
         format: int64
-        description: keep alive interval for policies owned by the service. 0 means no timeout supervision. Polcies that are not refreshed within this time are removed
+        description: 'keep alive interval for the service. This is a heartbeat supervision of the service, which in regular intevals must invoke a ''keepAlive'' REST call. When a service does not invoke this call within the given time, it is considered unavailble. An unavailable service will be automatically deregistered and its policies will be deleted. Value 0 means no timeout supervision.'
       serviceName:
         type: string
         description: identity of the service
@@ -896,7 +932,7 @@
       serviceName:
         type: string
         description: identity of the service
-      timeSincePingSeconds:
+      timeSinceLastActivitySeconds:
         type: integer
         format: int64
         description: time since last invocation by the service
diff --git a/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java b/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java
index bc3aa81..2520b0a 100644
--- a/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java
+++ b/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java
@@ -293,27 +293,30 @@
             return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
         }
         synchronized (policies) {
-            Collection<Policy> result = null;
+            String filteredPolicies = policiesToJson(filter(type, ric, service));
+            return new ResponseEntity<>(filteredPolicies, HttpStatus.OK);
+        }
+    }
 
-            if (type != null) {
-                result = policies.getForType(type);
-                result = filter(result, null, ric, service);
-            } else if (service != null) {
-                result = policies.getForService(service);
-                result = filter(result, type, ric, null);
-            } else if (ric != null) {
-                result = filter(policies.getForRic(ric), type, null, service);
-            } else {
-                result = policies.getAll();
-            }
-
-            String policiesJson;
-            try {
-                policiesJson = policiesToJson(result);
-            } catch (ServiceException e) {
-                return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
-            }
-            return new ResponseEntity<>(policiesJson, HttpStatus.OK);
+    @GetMapping("/policy_ids")
+    @ApiOperation(value = "Query policies, only IDs returned")
+    @ApiResponses(
+        value = {@ApiResponse(code = 200, message = "Policy ids", response = String.class, responseContainer = "List"),
+            @ApiResponse(code = 404, message = "RIC or type not found", response = String.class)})
+    public ResponseEntity<String> getPolicyIds( //
+        @RequestParam(name = "type", required = false) String type, //
+        @RequestParam(name = "ric", required = false) String ric, //
+        @RequestParam(name = "service", required = false) String service) //
+    {
+        if ((type != null && this.policyTypes.get(type) == null)) {
+            return new ResponseEntity<>("Policy type not found", HttpStatus.NOT_FOUND);
+        }
+        if ((ric != null && this.rics.get(ric) == null)) {
+            return new ResponseEntity<>("RIC not found", HttpStatus.NOT_FOUND);
+        }
+        synchronized (policies) {
+            String policyIdsJson = toPolicyIdsJson(filter(type, ric, service));
+            return new ResponseEntity<>(policyIdsJson, HttpStatus.OK);
         }
     }
 
@@ -363,7 +366,21 @@
         return filtered;
     }
 
-    private String policiesToJson(Collection<Policy> policies) throws ServiceException {
+    private Collection<Policy> filter(String type, String ric, String service) {
+        synchronized (policies) {
+            if (type != null) {
+                return filter(policies.getForType(type), null, ric, service);
+            } else if (service != null) {
+                return filter(policies.getForService(service), type, ric, null);
+            } else if (ric != null) {
+                return filter(policies.getForRic(ric), type, null, service);
+            } else {
+                return policies.getAll();
+            }
+        }
+    }
+
+    private String policiesToJson(Collection<Policy> policies) {
         List<PolicyInfo> v = new ArrayList<>(policies.size());
         for (Policy p : policies) {
             PolicyInfo policyInfo = new PolicyInfo();
@@ -374,7 +391,7 @@
             policyInfo.service = p.ownerServiceName();
             policyInfo.lastModified = p.lastModified();
             if (!policyInfo.validate()) {
-                throw new ServiceException("BUG, all fields must be set");
+                throw new NullPointerException("BUG, all fields must be set");
             }
             v.add(policyInfo);
         }
@@ -408,6 +425,14 @@
         return gson.toJson(v);
     }
 
+    private String toPolicyIdsJson(Collection<Policy> policies) {
+        List<String> v = new ArrayList<>(policies.size());
+        for (Policy p : policies) {
+            v.add(p.id());
+        }
+        return gson.toJson(v);
+    }
+
     private String getTimeStampUtc() {
         return java.time.Instant.now().toString();
     }
diff --git a/policy-agent/src/test/java/org/oransc/policyagent/ApplicationTest.java b/policy-agent/src/test/java/org/oransc/policyagent/ApplicationTest.java
index 5b6c5ba..55b0b43 100644
--- a/policy-agent/src/test/java/org/oransc/policyagent/ApplicationTest.java
+++ b/policy-agent/src/test/java/org/oransc/policyagent/ApplicationTest.java
@@ -497,6 +497,32 @@
     }
 
     @Test
+    public void testGetPolicyIdsFilter() throws Exception {
+        addPolicy("id1", "type1", "service1", "ric1");
+        addPolicy("id2", "type1", "service2", "ric1");
+        addPolicy("id3", "type2", "service1", "ric1");
+
+        String url = "/policy_ids?type=type1";
+        String rsp = restClient().get(url).block();
+        logger.info(rsp);
+        assertThat(rsp).contains("id1");
+        assertThat(rsp).contains("id2");
+        assertThat(rsp.contains("id3")).isFalse();
+
+        url = "/policy_ids?type=type1&service=service1&ric=ric1";
+        rsp = restClient().get(url).block();
+        assertThat(rsp).isEqualTo("[\"id1\"]");
+
+        // Test get policy ids for non existing type
+        url = "/policy_ids?type=type1XXX";
+        testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
+
+        // Test get policy ids for non existing RIC
+        url = "/policy_ids?ric=XXX";
+        testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
+    }
+
+    @Test
     public void testPutAndGetService() throws Exception {
         // PUT
         putService("name", 0);
diff --git a/policy-agent/src/test/java/org/oransc/policyagent/MockPolicyAgent.java b/policy-agent/src/test/java/org/oransc/policyagent/MockPolicyAgent.java
index efbd576..481a1fe 100644
--- a/policy-agent/src/test/java/org/oransc/policyagent/MockPolicyAgent.java
+++ b/policy-agent/src/test/java/org/oransc/policyagent/MockPolicyAgent.java
@@ -129,15 +129,13 @@
     @LocalServerPort
     private int port;
 
-    private void keepServerAlive() {
+    private void keepServerAlive() throws InterruptedException {
         logger.info("Keeping server alive!");
-        try {
-            synchronized (this) {
-                this.wait();
-            }
-        } catch (Exception ex) {
-            logger.error("Unexpected: " + ex);
+
+        synchronized (this) {
+            this.wait();
         }
+
     }
 
     private static String title(String jsonSchema) {
@@ -147,7 +145,8 @@
     }
 
     @Test
-    @SuppressWarnings("squid:S2699") // Tests should include assertions. This test is only for keeping the server alive,
+    @SuppressWarnings("squid:S2699") // Tests should include assertions. This test is only for keeping the server
+                                     // alive,
                                      // so it will only be confusing to add an assertion.
     public void runMock() throws Exception {
         keepServerAlive();