Added a getPolicies query REST call 57/1957/3
authorPatrikBuhr <patrik.buhr@est.tech>
Fri, 6 Dec 2019 16:23:16 +0000 (17:23 +0100)
committerPatrikBuhr <patrik.buhr@est.tech>
Mon, 9 Dec 2019 08:28:28 +0000 (09:28 +0100)
Change-Id: I354cb7cbb68ca69c5fe2e695bd66ec60eed43ead
Issue-ID: NONRTRIC-84
Signed-off-by: PatrikBuhr <patrik.buhr@est.tech>
policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyController.java
policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyInfo.java [new file with mode: 0644]
policy-agent/src/main/java/org/oransc/policyagent/controllers/RicInfo.java
policy-agent/src/main/java/org/oransc/policyagent/repository/Policies.java
policy-agent/src/main/java/org/oransc/policyagent/repository/PolicyTypes.java
policy-agent/src/main/java/org/oransc/policyagent/repository/Service.java [new file with mode: 0644]
policy-agent/src/main/java/org/oransc/policyagent/repository/Services.java [new file with mode: 0644]
policy-agent/src/test/java/org/oransc/policyagent/ApplicationTest.java

index 21521b7..4b3c9cf 100644 (file)
  */
 package org.oransc.policyagent.controllers;
 
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import java.util.Collection;
+import java.util.Vector;
+
 import org.oransc.policyagent.configuration.ApplicationConfig;
 import org.oransc.policyagent.exceptions.ServiceException;
 import org.oransc.policyagent.repository.ImmutablePolicy;
@@ -40,6 +46,9 @@ public class PolicyController {
     private final ApplicationConfig appConfig;
     private final PolicyTypes types;
     private final Policies policies;
+    private static Gson gson = new GsonBuilder() //
+        .serializeNulls() //
+        .create(); //
 
     @Autowired
     PolicyController(ApplicationConfig config, PolicyTypes types, Policies policies) {
@@ -48,13 +57,71 @@ public class PolicyController {
         this.policies = policies;
     }
 
-    // http://localhost:8080/policy?type=type3&instance=xxx
     @GetMapping("/policy")
     public ResponseEntity<String> getPolicy( //
-        @RequestParam(name = "type", required = false, defaultValue = "type1") String typeName, //
-        @RequestParam(name = "instance", required = false, defaultValue = "new") String instanceId) {
+        @RequestParam(name = "instance", required = false, defaultValue = "new") String instance) {
+        try {
+            Policy p = policies.get(instance);
+            return new ResponseEntity<String>(p.json(), HttpStatus.OK);
 
-        return new ResponseEntity<String>("policy" + typeName + instanceId, HttpStatus.OK);
+        } catch (ServiceException e) {
+            return new ResponseEntity<String>(e.getMessage(), HttpStatus.NO_CONTENT);
+        }
+    }
+
+    @GetMapping("/policies")
+    public ResponseEntity<String> getPolicies( //
+        @RequestParam(name = "type", required = false) String type, //
+        @RequestParam(name = "ric", required = false) String ric, //
+        @RequestParam(name = "service", required = false) String service) //
+    {
+        Collection<Policy> result = null;
+
+        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 = policies.getForRic(ric);
+            result = filter(result, type, null, service);
+        } else {
+            result = policies.getAll();
+        }
+
+        return new ResponseEntity<String>(toJson(result), HttpStatus.OK);
+    }
+
+    private boolean include(String filter, String value) {
+        return filter == null || value.equals(filter);
+    }
+
+    private Collection<Policy> filter(Collection<Policy> collection, String type, String ric, String service) {
+        if (type == null && ric == null && service == null) {
+            return collection;
+        }
+        Vector<Policy> filtered = new Vector<>();
+        for (Policy p : collection) {
+            if (include(type, p.type().name()) && include(ric, p.ric().name())
+                && include(service, p.ownerServiceName())) {
+                filtered.add(p);
+            }
+        }
+        return filtered;
+    }
+
+    private String toJson(Collection<Policy> policies) {
+        Vector<PolicyInfo> v = new Vector<>(policies.size());
+        for (Policy p : policies) {
+            PolicyInfo policyInfo = ImmutablePolicyInfo.builder() //
+                .json(p.json()) //
+                .name(p.id()) //
+                .ric(p.ric().name()) //
+                .type(p.type().name()).build();
+            v.add(policyInfo);
+        }
+        return gson.toJson(v);
     }
 
     @PutMapping(path = "/policy")
@@ -65,8 +132,6 @@ public class PolicyController {
         @RequestParam(name = "service", required = true) String service, //
         @RequestBody String jsonBody) {
 
-        System.out.println("*********************** " + jsonBody);
-
         try {
             Policy policy = ImmutablePolicy.builder() //
                 .id(instanceId) //
@@ -75,25 +140,11 @@ public class PolicyController {
                 .ric(appConfig.getRic(ric)) //
                 .ownerServiceName(service) //
                 .build();
-            policies.put(instanceId, policy);
+            policies.put(policy);
             return new ResponseEntity<String>(HttpStatus.OK);
         } catch (ServiceException e) {
-            System.out.println("*********************** " + e.getMessage());
-
             return new ResponseEntity<String>(e.getMessage(), HttpStatus.NOT_FOUND);
         }
-
-    }
-
-    @PutMapping(path = "/policyX")
-    public ResponseEntity<String> putPolicyX( //
-        // @RequestParam(name = "type", required = false) String type, //
-        // @RequestParam(name = "instance", required = true) String instance, //
-        // @RequestParam(name = "ric", required = true) String ric, //
-        @RequestBody String jsonBody) {
-        System.out.println("*********************** " + jsonBody);
-        // System.out.println("policy" + type + instance);
-        return new ResponseEntity<String>(HttpStatus.OK);
     }
 
 }
diff --git a/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyInfo.java b/policy-agent/src/main/java/org/oransc/policyagent/controllers/PolicyInfo.java
new file mode 100644 (file)
index 0000000..040ca3a
--- /dev/null
@@ -0,0 +1,42 @@
+/*-
+ * ========================LICENSE_START=================================
+ * O-RAN-SC
+ * %%
+ * Copyright (C) 2019 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
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ========================LICENSE_END===================================
+ */
+package org.oransc.policyagent.controllers;
+
+import com.google.gson.annotations.SerializedName;
+
+import org.immutables.gson.Gson;
+import org.immutables.value.Value;
+
+@Value.Immutable
+@Gson.TypeAdapters
+public interface PolicyInfo {
+
+    @SerializedName("id")
+    public String name();
+
+    @SerializedName("type")
+    public String type();
+
+    @SerializedName("ric")
+    public String ric();
+
+    @SerializedName("json")
+    public String json();
+}
index 843153a..3d59e68 100644 (file)
@@ -19,6 +19,8 @@
  */
 package org.oransc.policyagent.controllers;
 
+import com.google.gson.annotations.SerializedName;
+
 import java.util.Vector;
 
 import org.immutables.gson.Gson;
@@ -27,7 +29,10 @@ import org.immutables.value.Value;
 @Value.Immutable
 @Gson.TypeAdapters
 public interface RicInfo {
+
+    @SerializedName("name")
     public String name();
 
+    @SerializedName("nodeNames")
     public Vector<String> managedElementIds();
 }
index a5519ca..cddd8a3 100644 (file)
 
 package org.oransc.policyagent.repository;
 
+import java.util.Collection;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Vector;
 
+import org.oransc.policyagent.exceptions.ServiceException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
 
 public class Policies {
     private static final Logger logger = LoggerFactory.getLogger(Policies.class);
 
-    private Map<String, Policy> policies = new HashMap<String, Policy>();
+    private Map<String, Policy> policiesId = new HashMap<>();
+    private Map<String, Map<String, Policy>> policiesRic = new HashMap<>();
+    private Map<String, Map<String, Policy>> policiesService = new HashMap<>();
+    private Map<String, Map<String, Policy>> policiesType = new HashMap<>();
 
-    @Autowired
     public Policies() {
     }
 
-    public synchronized void put(String id, Policy policy) {
-        policies.put(id, policy);
+    public synchronized void put(Policy policy) {
+        policiesId.put(policy.id(), policy);
+        multiMapPut(policiesRic, policy.ric().name(), policy);
+        multiMapPut(policiesService, policy.ownerServiceName(), policy);
+        multiMapPut(policiesType, policy.type().name(), policy);
     }
 
-    public synchronized Policy get(String id) {
-        return policies.get(id);
+    private void multiMapPut(Map<String, Map<String, Policy>> multiMap, String key, Policy value) {
+        Map<String, Policy> map = multiMap.get(key);
+        if (map == null) {
+            map = new HashMap<>();
+            multiMap.put(key, map);
+        }
+        map.put(value.id(), value);
+    }
+
+    private void multiMapRemove(Map<String, Map<String, Policy>> multiMap, String key, Policy value) {
+        Map<String, Policy> map = multiMap.get(key);
+        if (map != null) {
+            map.remove(value.id());
+            if (map.isEmpty()) {
+                multiMap.remove(key);
+            }
+        }
+    }
+
+    private Collection<Policy> multiMapGet(Map<String, Map<String, Policy>> multiMap, String key) {
+        Map<String, Policy> map = multiMap.get(key);
+        if (map == null) {
+            return new Vector<Policy>();
+        }
+        return map.values();
+    }
+
+    public synchronized Policy get(String id) throws ServiceException {
+        Policy p = policiesId.get(id);
+        if (p == null) {
+            throw new ServiceException("Could not find policy: " + id);
+        }
+        return p;
+    }
+
+    public synchronized Collection<Policy> getAll() {
+        return policiesId.values();
+    }
+
+    public synchronized Collection<Policy> getForService(String service) {
+        return multiMapGet(policiesService, service);
+    }
+
+    public synchronized Collection<Policy> getForRic(String ric) {
+        return multiMapGet(policiesRic, ric);
+    }
+
+    public synchronized Collection<Policy> getForType(String type) {
+        return multiMapGet(policiesType, type);
+    }
+
+    public synchronized Policy removeId(String id) {
+        Policy p = policiesId.get(id);
+        if (p == null) {
+            remove(p);
+        }
+        return p;
+    }
+
+    public synchronized void remove(Policy policy) {
+        policiesId.remove(policy.id());
+        multiMapRemove(policiesRic, policy.ric().name(), policy);
+        multiMapRemove(policiesService, policy.ownerServiceName(), policy);
+        multiMapRemove(policiesType, policy.type().name(), policy);
+
     }
 
 }
index ef3f42d..dc299b6 100644 (file)
@@ -26,14 +26,12 @@ import java.util.Map;
 import org.oransc.policyagent.exceptions.ServiceException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
 
 public class PolicyTypes {
     private static final Logger logger = LoggerFactory.getLogger(PolicyTypes.class);
 
     private Map<String, PolicyType> types = new HashMap<String, PolicyType>();
 
-    @Autowired
     public PolicyTypes() {
     }
 
@@ -45,8 +43,8 @@ public class PolicyTypes {
         return t;
     }
 
-    public synchronized void putType(String name, PolicyType type) {
-        types.put(name, type);
+    public synchronized void put(PolicyType type) {
+        types.put(type.name(), type);
     }
 
 }
diff --git a/policy-agent/src/main/java/org/oransc/policyagent/repository/Service.java b/policy-agent/src/main/java/org/oransc/policyagent/repository/Service.java
new file mode 100644 (file)
index 0000000..8efa542
--- /dev/null
@@ -0,0 +1,24 @@
+/*-
+ * ========================LICENSE_START=================================
+ * O-RAN-SC
+ * %%
+ * Copyright (C) 2019 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
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ========================LICENSE_END===================================
+ */
+package org.oransc.policyagent.repository;
+
+public interface Service {
+
+}
diff --git a/policy-agent/src/main/java/org/oransc/policyagent/repository/Services.java b/policy-agent/src/main/java/org/oransc/policyagent/repository/Services.java
new file mode 100644 (file)
index 0000000..5b5b4a8
--- /dev/null
@@ -0,0 +1,37 @@
+/*-
+ * ========================LICENSE_START=================================
+ * O-RAN-SC
+ * %%
+ * Copyright (C) 2019 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
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ========================LICENSE_END===================================
+ */
+
+package org.oransc.policyagent.repository;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class Services {
+    private static final Logger logger = LoggerFactory.getLogger(Services.class);
+
+    private Map<String, Service> services = new HashMap<>();
+
+    public Services() {
+    }
+
+}
index d22a9da..d8ff2e1 100644 (file)
 package org.oransc.policyagent;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertFalse;
 
 import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.oransc.policyagent.configuration.ApplicationConfig;
+import org.oransc.policyagent.exceptions.ServiceException;
+import org.oransc.policyagent.repository.ImmutablePolicy;
 import org.oransc.policyagent.repository.ImmutablePolicyType;
 import org.oransc.policyagent.repository.Policies;
 import org.oransc.policyagent.repository.Policy;
@@ -39,9 +40,8 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
 import org.springframework.boot.test.context.TestConfiguration;
 import org.springframework.boot.web.server.LocalServerPort;
 import org.springframework.context.annotation.Bean;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.MediaType;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
 import org.springframework.test.context.junit4.SpringRunner;
 import org.springframework.web.client.RestTemplate;
 
@@ -88,19 +88,10 @@ public class ApplicationTest {
 
     private RestTemplate restTemplate = new RestTemplate();
 
-    @Test
-    public void getPolicy() throws Exception {
-        String cmd = "/policy?type=type3&instance=xxx";
-        String rsp = this.restTemplate.getForObject("http://localhost:" + port + cmd, String.class);
-        System.out.println("*** rsp " + rsp);
-        assertThat(rsp).contains("type3");
-    }
-
     @Test
     public void getRics() throws Exception {
         String cmd = "/rics";
         String rsp = this.restTemplate.getForObject("http://localhost:" + port + cmd, String.class);
-        System.out.println("*** rsp " + rsp);
         assertThat(rsp).contains("kista_1");
     }
 
@@ -115,36 +106,86 @@ public class ApplicationTest {
 
     @Test
     public void putPolicy() throws Exception {
-        // types.putType("type1", ImmutablePolicyType.builder().name("").jsonSchema("").build());
-
-        String url = "http://localhost:" + port + "/policy?type={type}&instance={instance}&ric={ric}&service={service}";
-
-        Map<String, String> uriVariables = new HashMap<String, String>();
-        uriVariables.put("type", "type1");
-        uriVariables.put("instance", "instance1");
-        uriVariables.put("ric", "ric1");
-        uriVariables.put("service", "service");
-        HttpHeaders headers = new HttpHeaders();
-        headers.setContentType(MediaType.APPLICATION_JSON);
+        String url = "http://localhost:" + port + "/policy?type=type1&instance=instance1&ric=ric1&service=service1";
         String json = "{}";
-        HttpEntity<String> entity = new HttpEntity<String>(json);
+        addPolicyType("type1");
 
-        addPolicyType(policyTypes, "type1");
-
-        this.restTemplate.put(url, entity, uriVariables);
+        this.restTemplate.put(url, json);
         Policy policy = this.policies.get("instance1");
+
         assertThat(policy).isNotNull();
         assertThat(policy.id()).isEqualTo("instance1");
-        assertThat(policy.ownerServiceName()).isEqualTo("service");
+        assertThat(policy.ownerServiceName()).isEqualTo("service1");
     }
 
-    private void addPolicyType(PolicyTypes policyTypes, String name) {
+    private PolicyType addPolicyType(String name) {
         PolicyType type = ImmutablePolicyType.builder() //
             .jsonSchema("") //
             .name(name) //
             .build();
 
-        policyTypes.putType(name, type);
+        policyTypes.put(type);
+        return type;
+    }
+
+    private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
+        Policy p = ImmutablePolicy.builder().id(id) //
+            .json("{}") //
+            .ownerServiceName(service) //
+            .ric(appConfig.getRic("ric1")) //
+            .type(addPolicyType(typeName)) //
+            .build();
+        this.policies.put(p);
+        return p;
+    }
+
+    @Test
+    public void getPolicy() throws Exception {
+        String url = "http://localhost:" + port + "/policy?instance=id";
+        Policy policy = addPolicy("id", "typeName", "service1");
+        {
+            String rsp = this.restTemplate.getForObject(url, String.class);
+            assertThat(rsp).isEqualTo(policy.json());
+        }
+        {
+            this.policies.remove(policy);
+            ResponseEntity<String> rsp = this.restTemplate.getForEntity(url, String.class);
+            assertThat(rsp.getStatusCodeValue()).isEqualTo(HttpStatus.NO_CONTENT.value());
+        }
+    }
+
+    @Test
+    public void getPolicies() throws Exception {
+        String url = "http://localhost:" + port + "/policies";
+        addPolicy("id1", "type1", "service1");
+        addPolicy("id2", "type2", "service2");
+
+        String rsp = this.restTemplate.getForObject(url, String.class);
+        System.out.println(rsp);
+        assertThat(rsp).contains("id1");
+        assertThat(rsp).contains("id2");
+    }
+
+    @Test
+    public void getPoliciesFilter() throws Exception {
+        String url = "http://localhost:" + port + "/policies?type=type1";
+        addPolicy("id1", "type1", "service1");
+        addPolicy("id2", "type1", "service2");
+        addPolicy("id3", "type2", "service1");
+
+        String rsp = this.restTemplate.getForObject(url, String.class);
+        System.out.println(rsp);
+        assertThat(rsp).contains("id1");
+        assertThat(rsp).contains("id2");
+        assertFalse(rsp.contains("id3"));
+
+        url = "http://localhost:" + port + "/policies?type=type1&service=service2";
+        rsp = this.restTemplate.getForObject(url, String.class);
+        System.out.println(rsp);
+        assertFalse(rsp.contains("id1"));
+        assertThat(rsp).contains("id2");
+        assertFalse(rsp.contains("id3"));
+
     }
 
 }