Fix bugs of policy adapters. 28/131528/2
authorzhangfan345 <zhangfan345@huawei.com>
Tue, 18 Oct 2022 02:33:05 +0000 (10:33 +0800)
committerKeguang He <hekeguang@chinamobile.com>
Thu, 20 Oct 2022 10:25:42 +0000 (10:25 +0000)
Issue-ID: USECASEUI-741
Signed-off-by: zhangfan345 <zhangfan345@huawei.com>
Change-Id: Ic57e04f1cd94f4d0767e2c4563654821d65fc10c

intentanalysis/src/main/java/org/onap/usecaseui/intentanalysis/adapters/policy/PolicyService.java
intentanalysis/src/main/java/org/onap/usecaseui/intentanalysis/adapters/policy/apicall/PolicyAPICall.java
intentanalysis/src/main/java/org/onap/usecaseui/intentanalysis/adapters/policy/impl/PolicyServiceImpl.java
intentanalysis/src/main/java/org/onap/usecaseui/intentanalysis/adapters/so/SOService.java
intentanalysis/src/main/java/org/onap/usecaseui/intentanalysis/adapters/so/apicall/SOAPICall.java
intentanalysis/src/main/java/org/onap/usecaseui/intentanalysis/adapters/so/impl/SOServiceImpl.java
intentanalysis/src/main/resources/application.yaml
intentanalysis/src/main/resources/intent-analysis-data.sql [new file with mode: 0644]
intentanalysis/src/test/java/org/onap/usecaseui/intentanalysis/adapters/policy/PolicyServiceTest.java
intentanalysis/src/test/resources/intentdb-test-data.sql

index 4511ed0..e5bc0bd 100644 (file)
@@ -37,6 +37,6 @@ public interface PolicyService {
      * @param closedLoopStatus  True: start  monitor, False: stop monitor
      * @return
      */
-    boolean updateIntentConfigPolicy(String cllId, String originalBW, boolean closedLoopStatus);
+    boolean updateIntentConfigPolicy(String cllId, String originalBW, String closedLoopStatus);
 
 }
index 8240661..4b38ebf 100644 (file)
@@ -39,9 +39,9 @@ public interface PolicyAPICall {
         "Accept: application/json",
         "Content-Type: application/json"
     })
-    @POST("/policy/api/v1/policytypes/{policyType}/versions/{policyTypeVersion}/policies")
+    @POST("/policy/api/v1/policytypes/{policyType}/versions/{policyVersion}/policies")
     Call<ResponseBody> createPolicy(@Path("policyType") String policyType,
-        @Path("policyTypeVersion") String policyTypeVersion, @Body RequestBody body);
+        @Path("policyVersion") String policyVersion, @Body RequestBody body);
 
     @Headers({
         "Accept: application/json",
index d51d338..97fb1ef 100644 (file)
@@ -19,6 +19,10 @@ package org.onap.usecaseui.intentanalysis.adapters.policy.impl;
 import java.io.File;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+
+import com.alibaba.fastjson2.JSONArray;
+import com.alibaba.fastjson2.JSONObject;
 import okhttp3.MediaType;
 import okhttp3.RequestBody;
 import okhttp3.ResponseBody;
@@ -41,13 +45,15 @@ public class PolicyServiceImpl implements PolicyService {
 
     private PolicyAPICall policyAPICall;
 
+    private static StringBuilder policyVersion = new StringBuilder("0.0.0") ;
+
     @Autowired
     PolicyAuthConfig policyAuthConfig;
 
     public PolicyAPICall getPolicyAPICall() {
         if (null == policyAPICall) {
             this.policyAPICall = RestfulServices.create(PolicyAPICall.class, policyAuthConfig.getUserName(),
-                policyAuthConfig.getPassword());
+                    policyAuthConfig.getPassword());
         }
         return this.policyAPICall;
     }
@@ -65,9 +71,9 @@ public class PolicyServiceImpl implements PolicyService {
             logger.info(String.format("Create policy, request body: %s", policyBody));
             RequestBody policyReq = RequestBody.create(MediaType.parse("application/json"), policyBody.toString());
             Response<ResponseBody> policyResponse = getPolicyAPICall().createPolicy(ModifyCLLPolicyConstants.policyType,
-                ModifyCLLPolicyConstants.policyTypeVersion, policyReq).execute();
+                    ModifyCLLPolicyConstants.policyTypeVersion, policyReq).execute();
             logger.info(String.format("Create policy result, code: %d body: %s", policyResponse.code(),
-                getResponseBodyStr(policyResponse)));
+                    getResponseBodyStr(policyResponse)));
             if (!policyResponse.isSuccessful()) {
                 logger.error("Create modify cll policy failed.");
                 return false;
@@ -78,10 +84,10 @@ public class PolicyServiceImpl implements PolicyService {
             String deployPolicyBody = FileUtils.readFileToString(deployPolicyFile, StandardCharsets.UTF_8);
             logger.info(String.format("Deploy policy, request body: %s", deployPolicyBody));
             RequestBody deployPolicyReq = RequestBody.create(MediaType.parse("application/json"),
-                deployPolicyBody.toString());
+                    deployPolicyBody.toString());
             Response<ResponseBody> deployPolicyResponse = getPolicyAPICall().deployPolicy(deployPolicyReq).execute();
             logger.info(String.format("Deploy policy result, code: %d body: %s", deployPolicyResponse.code(),
-                getResponseBodyStr(deployPolicyResponse)));
+                    getResponseBodyStr(deployPolicyResponse)));
             if (!deployPolicyResponse.isSuccessful()) {
                 logger.error("Deploy modify cll policy failed.");
                 return false;
@@ -97,20 +103,20 @@ public class PolicyServiceImpl implements PolicyService {
     @Override
     public boolean undeployAndRemoveModifyCLLPolicy() {
         return undeployAndRemovePolicyIfExist(ModifyCLLPolicyConstants.policyType,
-            ModifyCLLPolicyConstants.policyTypeVersion, ModifyCLLPolicyConstants.policyName,
-            ModifyCLLPolicyConstants.policyVersion);
+                ModifyCLLPolicyConstants.policyTypeVersion, ModifyCLLPolicyConstants.policyName,
+                ModifyCLLPolicyConstants.policyVersion);
     }
 
     @Override
-    public boolean updateIntentConfigPolicy(String cllId, String originalBW, boolean closedLoopStatus) {
+    public boolean updateIntentConfigPolicy(String cllId, String originalBW, String closedLoopStatus) {
         //the policy engine does not support update now. so we need to remove and recreate the policy now.
         logger.info(String.format(
-            "Start to update the intent configuration policy, cllId: %s, originalBW: %s, closedLooopStatus:%b", cllId,
-            originalBW, closedLoopStatus));
+                "Start to update the intent configuration policy, cllId: %s, originalBW: %s, closedLooopStatus:%b", cllId,
+                originalBW, closedLoopStatus));
         //remove the configuration policy first
         boolean res = undeployAndRemovePolicyIfExist(IntentConfigPolicyConstants.policyType,
-            IntentConfigPolicyConstants.policyTypeVersion, IntentConfigPolicyConstants.policyName,
-            IntentConfigPolicyConstants.policyVersion);
+                IntentConfigPolicyConstants.policyTypeVersion, IntentConfigPolicyConstants.policyName,
+                IntentConfigPolicyConstants.policyVersion);
         if (!res) {
             logger.warn("Undeploy and remove the intent configuration policy failed.");
         }
@@ -130,17 +136,17 @@ public class PolicyServiceImpl implements PolicyService {
      * @param closedLoopStatus
      * @return
      */
-    public boolean createAndDeployIntentConfigPolicy(String cllId, String originalBW, boolean closedLoopStatus) {
+    public boolean createAndDeployIntentConfigPolicy(String cllId, String originalBW, String closedLoopStatus) {
         try {
             //Create policy type
             File policyTypeFile = Resources.getResourceAsFile("intentPolicy/intent_configs_policy_type.json");
             String policyTypeBody = FileUtils.readFileToString(policyTypeFile, StandardCharsets.UTF_8);
             logger.info(String.format("Create policy type, request body: %s", policyTypeBody));
             RequestBody policyTypeReq = RequestBody.create(MediaType.parse("application/json"),
-                policyTypeBody.toString());
+                    policyTypeBody.toString());
             Response<ResponseBody> response = getPolicyAPICall().createPolicyType(policyTypeReq).execute();
             logger.info(String.format("Create policy type result, code: %d body: %s", response.code(),
-                getResponseBodyStr(response)));
+                    getResponseBodyStr(response)));
             if (!response.isSuccessful()) {
                 logger.error("Create intent configuration policy type failed.");
                 return false;
@@ -149,15 +155,16 @@ public class PolicyServiceImpl implements PolicyService {
             File policyFile = Resources.getResourceAsFile("intentPolicy/intent_configs_policy.json");
             String policyBodyTemplate = FileUtils.readFileToString(policyFile, StandardCharsets.UTF_8);
             String policyBody = policyBodyTemplate.replace("${CLL_ID}", cllId)
-                .replace("${CLOSED_LOOP_STATUS}", String.valueOf(closedLoopStatus))
-                .replace("${ORIGINAL_BW}", originalBW);
-            logger.info(String.format("Create policy, request body: %s", policyBody));
-            RequestBody policyReq = RequestBody.create(MediaType.parse("application/json"), policyBody.toString());
+                    .replace("${CLOSED_LOOP_STATUS}", closedLoopStatus)
+                    .replace("${ORIGINAL_BW}", originalBW);
+            String policyJsonBody = updatePolicyVersion(policyBody);
+            logger.info(String.format("Create policy, request body: %s", policyJsonBody));
+            RequestBody policyReq = RequestBody.create(MediaType.parse("application/json"), policyJsonBody);
             Response<ResponseBody> policyResponse = getPolicyAPICall().createPolicy(
-                    IntentConfigPolicyConstants.policyType, IntentConfigPolicyConstants.policyTypeVersion, policyReq)
-                .execute();
+                            IntentConfigPolicyConstants.policyType, policyVersion.toString(), policyReq)
+                    .execute();
             logger.info(String.format("Create policy result, code: %d body: %s", policyResponse.code(),
-                getResponseBodyStr(policyResponse)));
+                    getResponseBodyStr(policyResponse)));
             if (!policyResponse.isSuccessful()) {
                 logger.error("Create intent configuration policy failed.");
                 return false;
@@ -168,10 +175,10 @@ public class PolicyServiceImpl implements PolicyService {
             String deployPolicyBody = FileUtils.readFileToString(deployPolicyFile, StandardCharsets.UTF_8);
             logger.info(String.format("Deploy policy, request body: %s", deployPolicyBody));
             RequestBody deployPolicyReq = RequestBody.create(MediaType.parse("application/json"),
-                deployPolicyBody.toString());
+                    deployPolicyBody.toString());
             Response<ResponseBody> deployPolicyResponse = getPolicyAPICall().deployPolicy(deployPolicyReq).execute();
             logger.info(String.format("Deploy policy result, code: %d body: %s", deployPolicyResponse.code(),
-                getResponseBodyStr(deployPolicyResponse)));
+                    getResponseBodyStr(deployPolicyResponse)));
             if (!deployPolicyResponse.isSuccessful()) {
                 logger.error("Deploy intent configuration policy failed.");
                 return false;
@@ -190,24 +197,24 @@ public class PolicyServiceImpl implements PolicyService {
      * @return
      */
     private boolean undeployAndRemovePolicyIfExist(String policyType, String policyTypeVersion, String policyName,
-        String policyVersion) {
+                                                   String policyVersion) {
         try {
             //check if the policy exists
             Response<ResponseBody> response = getPolicyAPICall().getPolicy(policyType, policyTypeVersion, policyName,
-                policyVersion).execute();
+                    policyVersion).execute();
             logger.info(String.format("The policy query result, code: %d body: %s", response.code(),
-                getResponseBodyStr(response)));
+                    getResponseBodyStr(response)));
             // remove the policy if exists.
             if (response.isSuccessful()) {
                 logger.info("The policy exists, start to undeploy.");
                 Response<ResponseBody> undeployResponse = getPolicyAPICall().undeployPolicy(policyName).execute();
                 logger.info(String.format("Undeploy policy result. code: %d body: %s", undeployResponse.code(),
-                    getResponseBodyStr(undeployResponse)));
+                        getResponseBodyStr(undeployResponse)));
                 logger.info("Start to remove the policy.");
                 Response<ResponseBody> removeResponse = getPolicyAPICall().removePolicy(policyName, policyVersion)
-                    .execute();
+                        .execute();
                 logger.info(String.format("Remove policy result. code: %d body: %s", removeResponse.code(),
-                    getResponseBodyStr(removeResponse)));
+                        getResponseBodyStr(removeResponse)));
                 return true;
             }
             return true;
@@ -225,4 +232,24 @@ public class PolicyServiceImpl implements PolicyService {
         }
         return null;
     }
+
+    private String updatePolicyVersion(String policyBody) {
+        JSONObject policyJsonBody = JSONObject.parseObject(policyBody);
+        if (policyVersion.charAt(0) == '0') {
+            policyVersion.setCharAt(0, (char)(policyVersion.charAt(0) + 1));
+        }
+        else {
+            policyVersion.setCharAt(4, (char)(policyVersion.charAt(4) + 1));
+        }
+        JSONObject topologyTemplateObject = policyJsonBody.getJSONObject("topology_template");
+        JSONArray policiesArray = topologyTemplateObject.getJSONArray("policies");
+        JSONObject configObject = policiesArray.getJSONObject(0);
+        JSONObject versionObject = configObject.getJSONObject("onap.dcae.slicems.config");
+        versionObject.put("version", policyVersion.toString());
+        configObject.put("onap.dcae.slicems.config", versionObject);
+        policiesArray.set(0, configObject);
+        topologyTemplateObject.put("policies", policiesArray);
+        policyJsonBody.put("topology_template", topologyTemplateObject);
+        return policyJsonBody.toString();
+    }
 }
index 7b56e17..c95f16b 100644 (file)
@@ -18,10 +18,13 @@ package org.onap.usecaseui.intentanalysis.adapters.so;
 import org.onap.usecaseui.intentanalysis.bean.models.CCVPNInstance;
 import org.springframework.stereotype.Service;
 
+import java.util.Map;
+
 public interface SOService {
 
     int createCCVPNInstance(CCVPNInstance instance);
 
     int deleteIntentInstance(String instanceId);
 
+    int createIntentInstance(Map<String, Object> params);
 }
index cd07292..0d27cca 100644 (file)
@@ -25,15 +25,16 @@ public interface SOAPICall {
             "Accept: application/json",
             "Content-Type: application/json"
     })
-    @POST("/so/infra/serviceIntent/v1/create")
+    //@POST("/so/infra/serviceIntent/v1/create")
+    @POST("/api/usecaseui-server/v1/intent/createIntentInstance")
     Call<JSONObject> createIntentInstance(@Body RequestBody body);
 
     @Headers({
             "Accept: application/json",
             "Content-Type: application/json"
     })
-    @HTTP(method="DELETE", path="/so/infra/serviceIntent/v1/delete", hasBody = true)
-    Call<JSONObject> deleteIntentInstance(@Body RequestBody body);
+    @HTTP(method="DELETE", path="/api/usecaseui-server/v1/intent/deleteIntentInstance")
+    Call<JSONObject> deleteIntentInstance(@Query("instanceId") String instanceId);
 
 
 
index 6f5cbcc..0f80853 100644 (file)
@@ -20,7 +20,6 @@ import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import org.onap.usecaseui.intentanalysis.adapters.aai.apicall.AAIAPICall;
 import org.onap.usecaseui.intentanalysis.adapters.aai.apicall.AAIAuthConfig;
-import org.onap.usecaseui.intentanalysis.adapters.policy.apicall.PolicyAPICall;
 import org.onap.usecaseui.intentanalysis.adapters.so.SOService;
 import org.onap.usecaseui.intentanalysis.adapters.so.apicall.SOAPICall;
 import org.onap.usecaseui.intentanalysis.adapters.so.apicall.SOAuthConfig;
@@ -108,14 +107,27 @@ public class SOServiceImpl implements SOService {
     }
 
     @Override
-    public int deleteIntentInstance(String serviceInstanceId) {
+    public int deleteIntentInstance(String instanceId) {
         try {
-            deleteInstanceToSO(serviceInstanceId);
+            Response<JSONObject> response = getSoApiCall().deleteIntentInstance(instanceId.substring(4)).execute();
+            return 1;
         }catch (Exception e) {
             logger.error("delete instance to SO error :" + e);
             return 0;
         }
-        return 1;
+    }
+
+
+    @Override
+    public int createIntentInstance(Map<String, Object> params) {
+        try {
+            okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
+            Response<JSONObject> response = getSoApiCall().createIntentInstance(requestBody).execute();
+            return 1;
+        } catch (IOException e) {
+            logger.error("Details:" + e.getMessage());
+            return 0;
+        }
     }
 
     public String createIntentInstanceToSO(CCVPNInstance ccvpnInstance) throws IOException {
@@ -140,7 +152,7 @@ public class SOServiceImpl implements SOService {
         additionalProperties.put("enableSdnc", "true");
         params.put("additionalProperties", additionalProperties);
         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
-        getSoApiCall().deleteIntentInstance(requestBody).execute();
+        //getSoApiCall().deleteIntentInstance(requestBody).execute();
     }
 
     private int getCreateStatus(CCVPNInstance ccvpnInstance) throws IOException {
@@ -161,7 +173,7 @@ public class SOServiceImpl implements SOService {
 
     /**
      * parameter set up for ccpvpn instance creation
-      * @param ccvpnInstance
+     * @param ccvpnInstance
      * @return
      */
     private Map<String, Object> paramsSetUp(CCVPNInstance ccvpnInstance) {
index 39b03ae..6db6b46 100644 (file)
@@ -11,6 +11,7 @@ spring:
   sql:
     init:
       schema-locations: classpath*:intent-analysis-init.sql
+      data-locations: classpath*:intent-analysis-data.sql
       mode: always
 mybatis:
   configuration:
diff --git a/intentanalysis/src/main/resources/intent-analysis-data.sql b/intentanalysis/src/main/resources/intent-analysis-data.sql
new file mode 100644 (file)
index 0000000..c03f305
--- /dev/null
@@ -0,0 +1,6 @@
+-- ----------------------------
+-- Records of intent_management_function_reg_info
+-- ----------------------------
+INSERT INTO intent_management_function_reg_info(imfr_info_id, imfr_info_description, support_area, support_model, support_interfaces, handle_name, intent_function_type) VALUES ('CLLBusinessId','CLLBusiness','CLLBUSINESS',null,'CREATE,DELETE,UPDATE,SEARCH','CLLBusinessIntentManagementFunction','INTERNALFUNCTION');
+INSERT INTO intent_management_function_reg_info(imfr_info_id, imfr_info_description, support_area, support_model, support_interfaces, handle_name, intent_function_type) VALUES ('CLLDeliveryId','CLLDelivery','CLLBUSINESS,DELIVERY',null,'CREATE,DELETE,UPDATE,SEARCH','CLLDeliveryIntentManagementFunction','INTERNALFUNCTION');
+INSERT INTO intent_management_function_reg_info(imfr_info_id, imfr_info_description, support_area, support_model, support_interfaces, handle_name, intent_function_type) VALUES ('CLLAssuranceId','CLLAssurance','CLLBUSINESS,ASSURANCE',null,'CREATE,DELETE,UPDATE,SEARCH','CLLAssuranceIntentManagementFunction','INTERNALFUNCTION');
index ea253e7..2f9cf20 100644 (file)
@@ -101,35 +101,35 @@ public class PolicyServiceTest {
     @Test
     public void testUpdateIntentConfigPolicySuccess() throws IOException {
         mockUpPolicyApiCall(0);
-        boolean result = policyService.updateIntentConfigPolicy("testCLLID", "1000", true);
+        boolean result = policyService.updateIntentConfigPolicy("testCLLID", "1000", "true");
         Assert.assertTrue(result);
     }
 
     @Test
     public void testUpdateIntentConfigPolicySuccessPolicyNotExist(){
         mockUpPolicyApiCall(QUERY_POLICY_NOT_EXIST);
-        boolean result = policyService.updateIntentConfigPolicy("testCLLID", "1000", true);
+        boolean result = policyService.updateIntentConfigPolicy("testCLLID", "1000", "true");
         Assert.assertTrue(result);
     }
 
     @Test
     public void testUpdateIntentConfigPolicyFailedCreatePolicyTypeFailed(){
         mockUpPolicyApiCall(CREATE_POLICY_TYPE_FAILED);
-        boolean result = policyService.updateIntentConfigPolicy("testCLLID", "1000", true);
+        boolean result = policyService.updateIntentConfigPolicy("testCLLID", "1000", "true");
         Assert.assertFalse(result);
     }
 
     @Test
     public void testUpdateIntentConfigPolicyFailedCreatePolicyFailed(){
         mockUpPolicyApiCall(CREATE_POLICY_FAILED);
-        boolean result = policyService.updateIntentConfigPolicy("testCLLID", "1000", true);
+        boolean result = policyService.updateIntentConfigPolicy("testCLLID", "1000", "true");
         Assert.assertFalse(result);
     }
 
     @Test
     public void testUpdateIntentConfigPolicyFailedDeployPolicyFailed(){
         mockUpPolicyApiCall(DEPLOY_POLICY_FAILED);
-        boolean result = policyService.updateIntentConfigPolicy("testCLLID", "1000", true);
+        boolean result = policyService.updateIntentConfigPolicy("testCLLID", "1000", "true");
         Assert.assertFalse(result);
     }
 
index 78f4d1e..4a1f120 100644 (file)
@@ -106,10 +106,10 @@ values ('intentId2', 'NOT_FULFILLED', 'COMPLIANT', 'NotFulfilledReason');
 -- Records of intent_management_function_reg_info
 -- ----------------------------
 INSERT INTO intent_management_function_reg_info(imfr_info_id,imfr_info_description,support_area,support_model,support_interfaces,handle_name,intent_function_type)
-VALUES ('CLLBusinessId','CLLBusiness','CLLBUSINESS',null,'CREATE,DELETE,UPDATE,SEARCH}','CLLBusinessIntentManagementFunction','INTERNALFUNCTION');
+VALUES ('CLLBusinessId','CLLBusiness','CLLBUSINESS',null,'CREATE,DELETE,UPDATE,SEARCH','CLLBusinessIntentManagementFunction','INTERNALFUNCTION');
 
 INSERT INTO intent_management_function_reg_info(imfr_info_id,imfr_info_description,support_area,support_model,support_interfaces,handle_name,intent_function_type)
-VALUES ('CLLDeliveryId','CLLDelivery','CLLBUSINESS,DELIVERY',null,'CREATE,DELETE,UPDATE,SEARCH}','CLLDeliveryIntentManagementFunction','INTERNALFUNCTION');
+VALUES ('CLLDeliveryId','CLLDelivery','CLLBUSINESS,DELIVERY',null,'CREATE,DELETE,UPDATE,SEARCH','CLLDeliveryIntentManagementFunction','INTERNALFUNCTION');
 
 INSERT INTO intent_management_function_reg_info(imfr_info_id,imfr_info_description,support_area,support_model,support_interfaces,handle_name,intent_function_type)
 VALUES ('CLLAssuranceId','CLLAssurance','CLLBUSINESS,ASSURANCE',null,'CREATE,DELETE,UPDATE,SEARCH','CLLAssuranceIntentManagementFunction','INTERNALFUNCTION');
\ No newline at end of file