From 608d55685d920851c25523c2418b249811dbf0b7 Mon Sep 17 00:00:00 2001 From: ’zhaoyh6‘ Date: Thu, 10 Mar 2022 17:22:54 +0800 Subject: feat:Create an entry for the unified intent instance, save the instance information to AAI, and add test code. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue-ID: REQ-1075 Signed-off-by: ’zhaoyh6‘ Change-Id: Iae5d246441d06b8ba30cdde5b14ae2202d46b85a --- .../usecaseui/server/UuiServerApplication.java | 12 + .../server/bean/intent/CCVPNInstance.java | 11 + .../usecaseui/server/constant/IntentConstant.java | 35 ++ .../server/controller/IntentController.java | 198 ++++++--- .../server/service/intent/IntentApiService.java | 64 +++ .../service/intent/IntentInstanceService.java | 2 + .../server/service/intent/IntentResponseAOP.java | 2 +- .../server/service/intent/IntentService.java | 6 + .../intent/impl/IntentInstanceServiceImpl.java | 102 ++++- .../service/intent/impl/IntentServiceImpl.java | 120 ++++-- server/src/main/resources/application.properties | 2 + .../server/controller/IntentControllerTest.java | 119 +++++- .../intent/impl/IntentInstanceServiceImplTest.java | 461 ++++++++++++++++++++- .../service/intent/impl/IntentServiceImplTest.java | 129 +++++- .../src/main/assembly/config/ccvpn.properties | 21 + .../dbscripts/postgres/uui_create_table.sql | 5 +- 16 files changed, 1153 insertions(+), 136 deletions(-) create mode 100644 server/src/main/java/org/onap/usecaseui/server/constant/IntentConstant.java create mode 100644 standalone/src/main/assembly/config/ccvpn.properties diff --git a/server/src/main/java/org/onap/usecaseui/server/UuiServerApplication.java b/server/src/main/java/org/onap/usecaseui/server/UuiServerApplication.java index 39e37ec0..d7695144 100644 --- a/server/src/main/java/org/onap/usecaseui/server/UuiServerApplication.java +++ b/server/src/main/java/org/onap/usecaseui/server/UuiServerApplication.java @@ -21,10 +21,14 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration; +import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; +import org.springframework.util.unit.DataSize; import org.springframework.web.client.RestTemplate; +import javax.servlet.MultipartConfigElement; + @SpringBootApplication @EnableAutoConfiguration(exclude={JpaRepositoriesAutoConfiguration.class}) @ComponentScan(basePackages = "org.onap.usecaseui.server") @@ -41,6 +45,14 @@ public class UuiServerApplication { return new RestTemplate(); } + @Bean + public MultipartConfigElement multipartConfigElement() { + MultipartConfigFactory factory = new MultipartConfigFactory(); + factory.setMaxFileSize(DataSize.parse("512MB")); + factory.setMaxRequestSize(DataSize.parse("512MB")); + return factory.createMultipartConfig(); + } + public static void main(String[] args) { SpringApplication.run(UuiServerApplication.class, args); dmaapSubscriber.run(); diff --git a/server/src/main/java/org/onap/usecaseui/server/bean/intent/CCVPNInstance.java b/server/src/main/java/org/onap/usecaseui/server/bean/intent/CCVPNInstance.java index f9a56b97..50e5ac39 100644 --- a/server/src/main/java/org/onap/usecaseui/server/bean/intent/CCVPNInstance.java +++ b/server/src/main/java/org/onap/usecaseui/server/bean/intent/CCVPNInstance.java @@ -56,6 +56,9 @@ public class CCVPNInstance implements Serializable { @Column(name = "line_num") private String lineNum; + @Column(name = "protect_status") + private int protectStatus; + @Column(name = "delete_state") private int deleteState; @@ -158,4 +161,12 @@ public class CCVPNInstance implements Serializable { public void setDeleteState(int deleteState) { this.deleteState = deleteState; } + + public int getProtectStatus() { + return protectStatus; + } + + public void setProtectStatus(int protectStatus) { + this.protectStatus = protectStatus; + } } \ No newline at end of file diff --git a/server/src/main/java/org/onap/usecaseui/server/constant/IntentConstant.java b/server/src/main/java/org/onap/usecaseui/server/constant/IntentConstant.java new file mode 100644 index 00000000..9164176a --- /dev/null +++ b/server/src/main/java/org/onap/usecaseui/server/constant/IntentConstant.java @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2022 CTC, Inc. and others. All rights reserved. + * + * 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. + */ +package org.onap.usecaseui.server.constant; + +public final class IntentConstant { + public final static String UPLOADPATH = "/home/uui/upload/"; + public final static String NLPLOADPATH = "/home/uuihome/uui/bert-master/upload/"; + public final static String[] QUESTIONS_CCVPN = {"bandwidth", "access point", "cloud point"}; + public final static String[] QUESTIONS_5GS = {"Communication Service Name", "Max Number of UEs", "Data Rate Downlink", "Latency", "Data Rate Uplink", "Resource Sharing Level", "Mobility", "Area"}; + + public final static String MODEL_TYPE_CCVPN = "ccvpn"; + public final static String MODEL_TYPE_5GS = "5gs"; + + public final static String INTENT_INSTANCE_ID_PREFIX = "IBN"; + public final static String INTENT_INSTANCE_DATA_OWNER = "UUI"; + + public final static String NLP_HOST = "http://10.21.19.55"; + // public final static String NLP_HOST = "http://uui-nlp"; + public final static String NLP_ONLINE_URL_BASE = NLP_HOST+":33011"; + public final static String NLP_OFFLINE_URL_BASE = NLP_HOST+":33012"; + public final static String NLP_FILE_URL_BASE = NLP_HOST+":33013"; +} diff --git a/server/src/main/java/org/onap/usecaseui/server/controller/IntentController.java b/server/src/main/java/org/onap/usecaseui/server/controller/IntentController.java index 3dd3572c..ef1ebba3 100644 --- a/server/src/main/java/org/onap/usecaseui/server/controller/IntentController.java +++ b/server/src/main/java/org/onap/usecaseui/server/controller/IntentController.java @@ -19,6 +19,8 @@ import java.io.File; import java.io.IOException; import java.text.ParseException; import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javax.annotation.Resource; import com.alibaba.fastjson.JSONArray; @@ -27,6 +29,7 @@ import org.onap.usecaseui.server.bean.HttpResponseResult; import org.onap.usecaseui.server.bean.intent.CCVPNInstance; import org.onap.usecaseui.server.bean.intent.IntentModel; import org.onap.usecaseui.server.bean.intent.IntentResponseBody; +import org.onap.usecaseui.server.constant.IntentConstant; import org.onap.usecaseui.server.service.csmf.SlicingService; import org.onap.usecaseui.server.service.intent.IntentApiService; import org.onap.usecaseui.server.service.intent.IntentInstanceService; @@ -51,14 +54,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; @RequestMapping("/intent") public class IntentController { private final Logger logger = LoggerFactory.getLogger(IntentController.class); - private final static String UPLOADPATH = "/home/uui/upload/"; - private final static String NLPLOADPATH = "/home/uuihome/uui/bert-master/upload/"; - private final static String[] QUESTIONS_CCVPN = {"bandwidth", "access point", "cloud point"}; - private final static String[] QUESTIONS_5GS = {"Communication Service Name", "Max Number of UEs", "Data Rate Downlink", "Latency", "Data Rate Uplink", "Resource Sharing Level", "Mobility", "Area"}; - - private final static String MODEL_TYPE_CCVPN = "ccvpn"; - private final static String MODEL_TYPE_5GS = "5gs"; - @Resource(name = "IntentService") private IntentService intentService; @@ -91,9 +86,9 @@ public class IntentController { public String uploadModel (@RequestParam("file") MultipartFile file,@RequestParam("modelType")String modelType) { String fileName = file.getOriginalFilename(); - String filePath = UPLOADPATH + fileName ; + String filePath = IntentConstant.UPLOADPATH + fileName ; - File dest = new File(filePath); + File dest = newFile(filePath); if(!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); @@ -114,7 +109,7 @@ public class IntentController { model.setModelType(modelType); Map fileMap = new HashMap<>(); fileMap.put("file", filePath); - UploadFileUtil.formUpload("http://uui-nlp:33013/uploader", null, fileMap, null); + UploadFileUtil.formUpload(IntentConstant.NLP_FILE_URL_BASE + "/uploader", null, fileMap, null); intentService.addModel(model); @@ -135,9 +130,9 @@ public class IntentController { } String fileName = model.getModelName(); - String filePath = UPLOADPATH + fileName; + String filePath = IntentConstant.UPLOADPATH + fileName; logger.info("delete model file: " + filePath); - File dest = new File(filePath); + File dest = newFile(filePath); if(dest.exists()){ dest.delete(); postDeleteFile(fileName); @@ -156,7 +151,7 @@ public class IntentController { private String postDeleteFile(String fileName) { - String url = "http://uui-nlp:33013/deleteFile/"+ fileName; + String url = IntentConstant.NLP_FILE_URL_BASE + "/deleteFile/"+ fileName; HashMap headers = new HashMap<>(); HttpResponseResult result = HttpUtil.sendGetRequest(url,headers); @@ -178,7 +173,7 @@ public class IntentController { logger.info("active NLP model, model=" + model.getFilePath()); String fileName = intentService.activeModelFile(model); if (fileName != null) { - load(NLPLOADPATH + fileName); + intentService.load(IntentConstant.NLPLOADPATH + fileName); } @@ -191,26 +186,7 @@ public class IntentController { return result; } - private String load(String dirPath) { - String url = "http://uui-nlp:33011/api/online/load"; - HashMap headers = new HashMap<>(); - String bodyStr = "{" + "\"path\": \""+dirPath+"\"" + "}"; - logger.info("request body: " + bodyStr); - - HttpResponseResult result = HttpUtil.sendPostRequestByJson(url, headers, bodyStr); - String respContent = result.getResultContent(); - - logger.info("NLP api respond: " + String.valueOf(result.getResultCode())); - logger.info(respContent); - - JSONObject map = JSON.parseObject(respContent); - - String status = map.getString("Status"); - logger.info("load result: " + status); - - return status; - } @DeleteMapping(value = {"/deleteModel"}, produces = "application/json") public String deleteModel(@RequestParam String modelId){ @@ -227,12 +203,13 @@ public class IntentController { return result; } - + @IntentResponseBody @ResponseBody @PostMapping(value = {"/predict"}, consumes = MediaType.APPLICATION_JSON_VALUE, produces = "application/json; charset=utf-8") - public String predict(@RequestBody Object body) throws ParseException { + public Map predict(@RequestBody Object body) throws ParseException { String text = (String)((Map)body).get("text"); + text = text.trim(); String modelType = (String)((Map)body).get("modelType"); String activeModelType = intentService.getActiveModelType(); @@ -241,7 +218,7 @@ public class IntentController { } String[] questions = getQuestions(modelType); - String url = "http://uui-nlp:33011/api/online/predict"; + String url = IntentConstant.NLP_ONLINE_URL_BASE + "/api/online/predict"; HashMap headers = new HashMap<>(); String bodyStr = "{\"title\": \"predict\", \"text\": \"" + text + "\", \"questions\":" + new JSONArray(Arrays.asList(questions)).toJSONString() + "}"; @@ -257,44 +234,129 @@ public class IntentController { JSONObject map2 = new JSONObject(); - if (MODEL_TYPE_CCVPN.equals(modelType)) { - - String bandWidth = map.getString("bandwidth"); - String accessPoint = map.getString("access point"); - String cloudPoint = map.getString("cloud point"); - String instanceId = getUUID(); - String accessPointAlias = intentInstanceService.formatAccessPoint(accessPoint); - String bandwidthAlias = intentInstanceService.formatBandwidth(bandWidth); - String cloudPointAlias = intentInstanceService.formatCloudPoint(cloudPoint); - - Map accessPointOne = new HashMap<>(); - accessPointOne.put("name", accessPointAlias); - accessPointOne.put("bandwidth", bandwidthAlias); - map2.put("name", ""); - map2.put("instanceId", instanceId); - map2.put("accessPointOne", accessPointOne); - map2.put("cloudPointName", cloudPointAlias); + if (IntentConstant.MODEL_TYPE_CCVPN.equals(modelType)) { + assemblyCCVPNResult(text, map, map2); } else { - for (Map.Entry entry:map.entrySet()) { - logger.debug(entry.getKey()+","+entry.getValue()); - String key = tranlateFieldName(entry.getKey()); - String valueStr = (String) entry.getValue(); - String value = intentService.calcFieldValue(key, valueStr); - map2.put(key, value); - } + assemblySlicingResult(map, map2); } logger.info("translate result: " + map2.toJSONString()); - return map2.toJSONString(); + return map2; + } + + @IntentResponseBody + @ResponseBody + @PostMapping(value = {"/unifyPredict"}, consumes = MediaType.APPLICATION_JSON_VALUE, + produces = "application/json; charset=utf-8") + public Map unifyPredict(@RequestBody Object body) throws ParseException { + String text = (String)((Map)body).get("text"); + text = text.trim(); + String modelType = intentService.getModelTypeByIntentText(text); + + String activeModelType = intentService.getActiveModelType(); + if (modelType == null || !modelType.equals(activeModelType)) { + intentService.activeModelByType(modelType); + } + String[] questions = getQuestions(modelType); + + String url = IntentConstant.NLP_ONLINE_URL_BASE + "/api/online/predict"; + HashMap headers = new HashMap<>(); + String bodyStr = "{\"title\": \"predict\", \"text\": \"" + text + + "\", \"questions\":" + new JSONArray(Arrays.asList(questions)).toJSONString() + "}"; + logger.info("request body: " + bodyStr); + + HttpResponseResult result = HttpUtil.sendPostRequestByJson(url, headers, bodyStr); + String respContent = result.getResultContent(); + + logger.info("NLP api respond: " + String.valueOf(result.getResultCode())); + logger.info(respContent); + + JSONObject map = JSON.parseObject(respContent); + + JSONObject map2 = new JSONObject(); + JSONObject resultMap = new JSONObject(); + + if (IntentConstant.MODEL_TYPE_CCVPN.equals(modelType)) { + assemblyCCVPNResult(text, map, map2); + resultMap.put("type", IntentConstant.MODEL_TYPE_CCVPN); + } + else { + assemblySlicingResult(map, map2); + resultMap.put("type", IntentConstant.MODEL_TYPE_5GS); + } + resultMap.put("formData",map2); + + logger.info("translate result: " + resultMap.toJSONString()); + + return resultMap; + } + + private void assemblySlicingResult(JSONObject map, JSONObject resultMap) { + for (Map.Entry entry : map.entrySet()) { + logger.debug(entry.getKey() + "," + entry.getValue()); + String key = tranlateFieldName(entry.getKey()); + String valueStr = (String) entry.getValue(); + String value = intentService.calcFieldValue(key, valueStr); + resultMap.put(key, value); + } + } + + private void assemblyCCVPNResult(String text, JSONObject map, JSONObject map2) { + String bandWidth = map.getString("bandwidth"); + String accessPoint = map.getString("access point"); + String cloudPoint = map.getString("cloud point"); + boolean protect = MapUtils.getBooleanValue(map, "protect", false); + String instanceId = getUUID(); + String accessPointAlias = intentInstanceService.formatAccessPoint(accessPoint); + if ("".equals(accessPointAlias)) { + if (text.indexOf("Access one") > -1) { + accessPointAlias = "tranportEp_src_ID_111_1"; + } else if (text.indexOf("Access two") > -1) { + accessPointAlias = "tranportEp_src_ID_111_2"; + } else if (text.indexOf("Access three") > -1) { + accessPointAlias = "tranportEp_src_ID_113_1"; + } + } + String bandwidthAlias = null; + if (bandWidth.matches("\\d+")) { + bandwidthAlias = intentInstanceService.formatBandwidth(bandWidth); + } else { + Pattern pattern = Pattern.compile("(\\d+)(Gbps|Mbps)"); + Matcher matcher = pattern.matcher(text); + if (matcher.find()) { + int value = Integer.parseInt(matcher.group(1)); + String unit = matcher.group(2); + if ("Gbps".equals(unit)) { + value = value * 1000; + } + bandwidthAlias = value + ""; + } + } + + String cloudPointAlias = intentInstanceService.formatCloudPoint(cloudPoint); + if ("".equals(cloudPointAlias)) { + if (text.indexOf("Cloud one") > -1) { + cloudPointAlias = "tranportEp_dst_ID_212_1"; + } + } + + Map accessPointOne = new HashMap<>(); + accessPointOne.put("name", accessPointAlias); + accessPointOne.put("bandwidth", bandwidthAlias); + map2.put("name", ""); + map2.put("instanceId", instanceId); + map2.put("accessPointOne", accessPointOne); + map2.put("cloudPointName", cloudPointAlias); + map2.put("protect", protect); } private String[] getQuestions(String modelType) { - if (MODEL_TYPE_CCVPN.equals(modelType)) { - return QUESTIONS_CCVPN; + if (IntentConstant.MODEL_TYPE_CCVPN.equals(modelType)) { + return IntentConstant.QUESTIONS_CCVPN; } else { - return QUESTIONS_5GS; + return IntentConstant.QUESTIONS_5GS; } } @@ -361,6 +423,7 @@ public class IntentController { Map accessPointOne = (Map) ((Map)body).get("accessPointOne"); String accessPointOneName = MapUtils.getString(accessPointOne, "name"); int accessPointOneBandWidth = MapUtils.getIntValue(accessPointOne, "bandwidth"); + boolean protectStatus = MapUtils.getBooleanValue((Map)body,"protect", false); CCVPNInstance instance = new CCVPNInstance(); instance.setInstanceId(intentInstanceId); @@ -370,6 +433,7 @@ public class IntentController { instance.setAccessPointOneName(accessPointOneName); instance.setAccessPointOneBandWidth(accessPointOneBandWidth); instance.setStatus("0"); + instance.setProtectStatus(protectStatus?1:0); int flag = intentInstanceService.createIntentInstance(instance); @@ -446,4 +510,8 @@ public class IntentController { JSONArray ids= new JSONObject((Map)body).getJSONArray("ids"); return intentInstanceService.getInstanceStatus(ids); } + + public File newFile(String filePath) { + return new File(filePath); + } } diff --git a/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentApiService.java b/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentApiService.java index 4d526389..dba140a3 100644 --- a/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentApiService.java +++ b/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentApiService.java @@ -75,6 +75,70 @@ public interface IntentApiService { @GET("/aai/v24/business/customers/customer/IBNCustomer/service-subscriptions/service-subscription/IBN/service-instances/service-instance/{resource-service-id}") Call getInstanceInfo(@Path("resource-service-id") String resourceServiceId); + @Headers({ + "X-TransactionId: 9999", + "X-FromAppId: MSO", + "Authorization: Basic QUFJOkFBSQ==", + "Accept: application/json" + }) + @PUT("/aai/v24/business/customers/customer/{globalCustomerId}") + Call addCustomer(@Path("globalCustomerId") String globalCustomerId,@Body RequestBody body); + + @Headers({ + "X-TransactionId: 9999", + "X-FromAppId: MSO", + "Authorization: Basic QUFJOkFBSQ==", + "Accept: application/json" + }) + @GET("/aai/v24/business/customers/customer/{globalCustomerId}") + Call queryCustomer(@Path("globalCustomerId") String globalCustomerId); + @Headers({ + "X-TransactionId: 9999", + "X-FromAppId: MSO", + "Authorization: Basic QUFJOkFBSQ==", + "Accept: application/json" + }) + @PUT("/aai/v24/business/customers/customer/{globalCustomerId}/service-subscriptions/service-subscription/{serviceType}") + Call addSubscription(@Path("globalCustomerId") String globalCustomerId, @Path("serviceType") String serviceType,@Body RequestBody body); + + @Headers({ + "X-TransactionId: 9999", + "X-FromAppId: MSO", + "Authorization: Basic QUFJOkFBSQ==", + "Accept: application/json" + }) + @GET("/aai/v24/business/customers/customer/{globalCustomerId}/service-subscriptions/service-subscription/{serviceType}") + Call querySubscription(@Path("globalCustomerId") String globalCustomerId, @Path("serviceType") String serviceType); + + @Headers({ + "X-TransactionId: 9999", + "X-FromAppId: MSO", + "Authorization: Basic QUFJOkFBSQ==", + "Accept: application/json" + }) + @PUT("/aai/v24/business/customers/customer/{globalCustomerId}/service-subscriptions/service-subscription/{serviceType}/service-instances/service-instance/{serviceInstanceId}") + Call saveServiceInstance(@Path("globalCustomerId") String globalCustomerId, @Path("serviceType") String serviceType, @Path("serviceInstanceId") String serviceInstanceId, @Body RequestBody body); + + + @Headers({ + "X-TransactionId: 9999", + "X-FromAppId: MSO", + "Authorization: Basic QUFJOkFBSQ==", + "Accept: application/json" + }) + @GET("/aai/v24/business/customers/customer/{globalCustomerId}/service-subscriptions/service-subscription/{serviceType}/service-instances/service-instance/{serviceInstanceId}") + Call queryServiceInstance(@Path("globalCustomerId") String globalCustomerId, @Path("serviceType") String serviceType, @Path("serviceInstanceId") String serviceInstanceId); + + + @Headers({ + "X-TransactionId: 9999", + "X-FromAppId: MSO", + "Authorization: Basic QUFJOkFBSQ==", + "Accept: application/json" + }) + @DELETE("/aai/v24/business/customers/customer/{globalCustomerId}/service-subscriptions/service-subscription/{serviceType}/service-instances/service-instance/{serviceInstanceId}?resource-version={resourceVersion}") + Call deleteServiceInstance(@Path("globalCustomerId") String globalCustomerId, @Path("serviceType") String serviceType, @Path("serviceInstanceId") String serviceInstanceId, @Path("resourceVersion") String resourceVersion); + @Headers({ "Authorization: Basic SW5mcmFQb3J0YWxDbGllbnQ6cGFzc3dvcmQxJA==", "Accept: application/json" diff --git a/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentInstanceService.java b/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentInstanceService.java index 2491cc26..13362c16 100644 --- a/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentInstanceService.java +++ b/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentInstanceService.java @@ -49,4 +49,6 @@ public interface IntentInstanceService { String formatCloudPoint(String cloudPoint); String formatAccessPoint(String accessPoint); + + void addCustomer() throws IOException; } diff --git a/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentResponseAOP.java b/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentResponseAOP.java index aad3c6c7..b0cba2d2 100644 --- a/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentResponseAOP.java +++ b/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentResponseAOP.java @@ -37,7 +37,7 @@ public class IntentResponseAOP { resultData.setData(proceed); } catch (Exception e) { - resultData.setData(500); + resultData.setCode(500); resultData.setMessage("Error:" + e.getMessage()); } return JSONObject.parseObject(resultData.toString()); diff --git a/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentService.java b/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentService.java index dcc6a2da..2e56104a 100644 --- a/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentService.java +++ b/server/src/main/java/org/onap/usecaseui/server/service/intent/IntentService.java @@ -28,4 +28,10 @@ public interface IntentService { String activeModelFile(IntentModel model); String calcFieldValue(String key, String strValue); String getActiveModelType(); + + String getModelTypeByIntentText(String text); + + IntentModel activeModelByType(String modelType); + + String load(String s); } diff --git a/server/src/main/java/org/onap/usecaseui/server/service/intent/impl/IntentInstanceServiceImpl.java b/server/src/main/java/org/onap/usecaseui/server/service/intent/impl/IntentInstanceServiceImpl.java index 2e3c9614..3c04ec21 100644 --- a/server/src/main/java/org/onap/usecaseui/server/service/intent/impl/IntentInstanceServiceImpl.java +++ b/server/src/main/java/org/onap/usecaseui/server/service/intent/impl/IntentInstanceServiceImpl.java @@ -24,6 +24,7 @@ import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.onap.usecaseui.server.bean.intent.InstancePerformance; import org.onap.usecaseui.server.bean.intent.CCVPNInstance; +import org.onap.usecaseui.server.constant.IntentConstant; import org.onap.usecaseui.server.service.intent.IntentApiService; import org.onap.usecaseui.server.service.intent.IntentInstanceService; import org.onap.usecaseui.server.service.lcm.domain.so.SOService; @@ -35,10 +36,11 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.stereotype.Service; +import retrofit2.Call; import retrofit2.Response; import javax.transaction.Transactional; -import java.io.IOException; +import java.io.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; @@ -165,6 +167,7 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { } instance.setJobId(jobId); instance.setResourceInstanceId("cll-"+instance.getInstanceId()); + saveIntentInstanceToAAI(null, instance); tx = session.beginTransaction(); session.save(instance); @@ -181,7 +184,7 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { } } - private String createIntentInstanceToSO(CCVPNInstance instance) throws IOException { + public String createIntentInstanceToSO(CCVPNInstance instance) throws IOException { Map params = new HashMap<>(); params.put("name", instance.getName()); params.put("modelInvariantUuid", "6790ab0e-034f-11eb-adc1-0242ac120002"); @@ -228,6 +231,7 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { instance.setProgress(progress); if (progress >=100) { instance.setStatus("1"); + saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId(),instance); } } catch (Exception e) { @@ -246,6 +250,7 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { int flag = getCreateStatusByJobId(instance); if (flag > 0) { instance.setStatus(flag + ""); + saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId(),instance); } } catch (Exception e) { @@ -437,6 +442,7 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { try { String serviceInstanceId = result.getResourceInstanceId(); deleteInstanceToSO(serviceInstanceId); + deleteIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-"+instanceId); deleteInstance(result); }catch (Exception e) { logger.error("delete instance to SO error :" + e); @@ -687,4 +693,96 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { } return accessPointAlias; } + + public void addCustomer() throws IOException { + Properties environment = getProperties(); + String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId"); + Response queryCustomerResponse = intentApiService.queryCustomer(globalCustomerId).execute(); + if (queryCustomerResponse.isSuccessful()) { + return; + } + String subscriberName = environment.getProperty("ccvpn.subscriberName"); + String subscriberType = environment.getProperty("ccvpn.subscriberType"); + Map params = new HashMap<>(); + params.put("global-customer-id", globalCustomerId); + params.put("subscriber-name", subscriberName); + params.put("subscriber-type", subscriberType); + okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params)); + intentApiService.addCustomer(globalCustomerId, requestBody).execute(); + } + + public void addSubscription() throws IOException { + Properties environment = getProperties(); + String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId"); + String serviceType = environment.getProperty("ccvpn.serviceType"); + Response querySubscription = intentApiService.querySubscription(globalCustomerId, serviceType).execute(); + if (querySubscription.isSuccessful()) { + return; + } + Map params = new HashMap<>(); + params.put("service-type", serviceType); + okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params)); + intentApiService.addSubscription(globalCustomerId, serviceType, requestBody).execute(); + } + + public Properties getProperties() throws IOException { + String slicingPath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "ccvpn.properties"; + InputStream inputStream = new FileInputStream(new File(slicingPath)); + Properties environment = new Properties(); + environment.load(inputStream); + return environment; + } + + + public void saveIntentInstanceToAAI(String serviceInstanceId, CCVPNInstance instance) throws IOException { + addCustomer(); + addSubscription(); + Properties environment = getProperties(); + String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId"); + String serviceType = environment.getProperty("ccvpn.serviceType"); + String resourceVersion = null; + if (serviceInstanceId != null) { + Response queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute(); + if (queryServiceInstance.isSuccessful()) { + JSONObject body = queryServiceInstance.body(); + resourceVersion = body.getString("resource-version"); + } + } else { + serviceInstanceId = IntentConstant.MODEL_TYPE_CCVPN + "-" + instance.getInstanceId(); + } + JSONObject environmentContext = JSONObject.parseObject(JSONObject.toJSONString(instance)); + environmentContext.put("resourceInstanceId",instance.getResourceInstanceId()); + + Map params = new HashMap<>(); + params.put("service-instance-id", serviceInstanceId); + params.put("service-instance-name", instance.getName()); + params.put("service-type", IntentConstant.MODEL_TYPE_CCVPN); + params.put("environment-context", environmentContext); + params.put("service-instance-location-id", instance.getResourceInstanceId()); + params.put("bandwidth-total", instance.getAccessPointOneBandWidth()); + params.put("data-owner", IntentConstant.INTENT_INSTANCE_DATA_OWNER); + if (resourceVersion != null) { + params.put("resource-version",resourceVersion); + } + okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params)); + intentApiService.saveServiceInstance(globalCustomerId,serviceType,serviceInstanceId,requestBody).execute(); + + } + public void deleteIntentInstanceToAAI(String serviceInstanceId) throws IOException { + addCustomer(); + addSubscription(); + Properties environment = getProperties(); + String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId"); + String serviceType = environment.getProperty("ccvpn.serviceType"); + if (serviceInstanceId == null) { + return; + } + Response queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute(); + if (queryServiceInstance.isSuccessful()) { + JSONObject body = queryServiceInstance.body(); + String resourceVersion = body.getString("resource-version"); + intentApiService.deleteServiceInstance(globalCustomerId,serviceType,serviceInstanceId,resourceVersion).execute(); + } + } + } diff --git a/server/src/main/java/org/onap/usecaseui/server/service/intent/impl/IntentServiceImpl.java b/server/src/main/java/org/onap/usecaseui/server/service/intent/impl/IntentServiceImpl.java index 137b77a3..6d2911a7 100644 --- a/server/src/main/java/org/onap/usecaseui/server/service/intent/impl/IntentServiceImpl.java +++ b/server/src/main/java/org/onap/usecaseui/server/service/intent/impl/IntentServiceImpl.java @@ -24,12 +24,16 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.transaction.Transactional; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.onap.usecaseui.server.bean.HttpResponseResult; +import org.onap.usecaseui.server.bean.intent.CCVPNInstance; import org.onap.usecaseui.server.bean.intent.IntentModel; +import org.onap.usecaseui.server.constant.IntentConstant; import org.onap.usecaseui.server.service.intent.IntentService; import org.onap.usecaseui.server.util.HttpUtil; import org.slf4j.Logger; @@ -87,7 +91,7 @@ public class IntentServiceImpl implements IntentService { public List listModels(){ try(Session session = getSession()){ - StringBuffer hql =new StringBuffer("from IntentModel a where 1=1 "); + StringBuffer hql =new StringBuffer("from IntentModel a where 1=1 order by create_time "); Query query = session.createQuery(hql.toString()); //query.setString("sortType",sortType); List list= query.list(); @@ -186,7 +190,7 @@ public class IntentServiceImpl implements IntentService { else if (fileName.endsWith(".zip")){ try { postUnzipFile(fileName); - return fileName; + return fileName.substring(0,fileName.length()-4); } catch (Exception e) { @@ -198,7 +202,7 @@ public class IntentServiceImpl implements IntentService { private String postUnzipFile(String fileName) { - String url = "http://uui-nlp:33013/unzipFile/"+ fileName; + String url = IntentConstant.NLP_FILE_URL_BASE + "/unzipFile/"+ fileName; HashMap headers = new HashMap<>(); HttpResponseResult result = HttpUtil.sendGetRequest(url,headers); @@ -336,27 +340,27 @@ public class IntentServiceImpl implements IntentService { private String formatValueForCoverageArea(String strValue) { String ret; Map areaMap = new HashMap<>(); - areaMap.put("wanshoulu", "Beijing Haidian District Wanshoulu Street"); - areaMap.put("zhongguancun", "Beijing Haidian District Zhongguancun"); - areaMap.put("haidian", "Beijing Haidian District Haidian Street"); - areaMap.put("xisanqi", "Beijing Haidian District Xisanqi Street"); - areaMap.put("chengbei", "Beijing Changping District Chengbei Street"); - areaMap.put("chengnan", "Beijing Changping District Chengnan Street"); - areaMap.put("tiantongyuan north", "Beijing Changping District Tiantongyuan North Street"); - areaMap.put("tiantongyuan south", "Beijing Changping District Tiantongyuan South Street"); - areaMap.put("guang'anmenwai", "Beijing Xicheng District Guang'anmenwai Street"); - areaMap.put("xuanwumen", "Beijing Xicheng District Xuanwumen Street"); - areaMap.put("west changan", "Beijing Xicheng District West Changan Street"); - areaMap.put("financial", "Beijing Xicheng District Financial Street"); - areaMap.put("lujiazui", "Shanghai udongxin District Lujiazui Street"); - areaMap.put("zhoujiadu", "Shanghai udongxin District Zhoujiadu Street"); - areaMap.put("tangqiao", "Shanghai udongxin District Tangqiao Street"); - areaMap.put("nanquanlu", "Shanghai udongxin District Nanquanlu Street"); - areaMap.put("jiangning lu", "Shanghai Jingan District Jiangning Lu Street"); - areaMap.put("jing'an temple", "Shanghai Jingan District Jing'an Temple Street"); - areaMap.put("ningjing west road", "Shanghai Jingan District Ningjing West Road"); - - ret = "Beijing Beijing Haiding Wanshoulu"; + areaMap.put("wanshoulu", "Beijing;Beijing;Haidian District;Wanshoulu Street"); + areaMap.put("zhongguancun", "Beijing;Beijing;Haidian District;Zhongguancun Street"); + areaMap.put("haidian", "Beijing;Beijing;Haidian District;Haidian Street"); + areaMap.put("xisanqi", "Beijing;Beijing;Haidian District;Xisanqi Street"); + areaMap.put("chengbei", "Beijing;Beijing;Changping District;Chengbei Street"); + areaMap.put("chengnan", "Beijing;Beijing;Changping District;Chengnan Street"); + areaMap.put("tiantongyuan north", "Beijing;Beijing;Changping District;Tiantongyuan North Street"); + areaMap.put("tiantongyuan south", "Beijing;Beijing;Changping District;Tiantongyuan South Street"); + areaMap.put("guang'anmenwai", "Beijing;Beijing;Xicheng District;Guang'anmenwai Street"); + areaMap.put("xuanwumen", "Beijing;Beijing;Xicheng District;Xuanwumen Street"); + areaMap.put("west changan", "Beijing;Beijing;Xicheng District;West Changan Street"); + areaMap.put("financial", "Beijing;Beijing;Xicheng District;Financial Street"); + areaMap.put("lujiazui", "Shanghai;Shanghai city;Pudongxin District;Lujiazui Street"); + areaMap.put("zhoujiadu", "Shanghai;Shanghai city;Pudongxin District;Zhoujiadu Street"); + areaMap.put("tangqiao", "Shanghai;Shanghai city;Pudongxin District;Tangqiao Street"); + areaMap.put("nanquanlu", "Shanghai;Shanghai city;Pudongxin District;Nanquanlu Street"); + areaMap.put("jiangning lu", "Shanghai;Shanghai city;Jingan District;Jiangning Lu Street"); + areaMap.put("jing'an temple", "Shanghai;Shanghai city;Jingan District;Jing'an Temple Street"); + areaMap.put("ningjing west road", "Shanghai;Shanghai city;Jingan District;Ningjing West Road"); + + ret = "Beijing;Beijing;Haidian District;Wanshoulu Street"; for (Map.Entry entry : areaMap.entrySet()) { if (strValue.toLowerCase().contains(entry.getKey())) { @@ -400,4 +404,72 @@ public class IntentServiceImpl implements IntentService { return null; } } + + @Override + public String getModelTypeByIntentText(String text) { + Pattern ccvpnPattern = Pattern.compile("(CCVPN|ccvpn|Cloud|CLOUD|cloud)"); + Matcher matcher = ccvpnPattern.matcher(text); + if(matcher.find()) { + return IntentConstant.MODEL_TYPE_CCVPN; + } + return IntentConstant.MODEL_TYPE_5GS; + } + + @Override + public IntentModel activeModelByType(String modelType) { + Transaction tx = null; + IntentModel result=null; + try(Session session = getSession()){ + + tx = session.beginTransaction(); + List list = session.createQuery("from IntentModel where active=1").list(); + if(list!=null && list.size()>0){ + for (IntentModel m : list) { + m.setActive(0); + session.save(m); + } + } + + List listModelByType = session.createQuery("from IntentModel where modelType = :modelType order by createTime desc") + .setParameter("modelType", IntentConstant.MODEL_TYPE_CCVPN.equals(modelType)?1:0).list(); + if (listModelByType.isEmpty()) { + return null; + } + IntentModel model = listModelByType.get(0); + model.setActive(1); + session.save(model); + tx.commit(); + logger.info("active model OK, id=" + model.getId()); + String fileName = activeModelFile(model); + if (fileName != null) { + load(IntentConstant.NLPLOADPATH + fileName); + } + result = model; + return result; + } catch (Exception e) { + logger.error("Details:" + e.getMessage()); + return null; + } + } + @Override + public String load(String dirPath) { + + String url = IntentConstant.NLP_ONLINE_URL_BASE + "/api/online/load"; + HashMap headers = new HashMap<>(); + String bodyStr = "{" + "\"path\": \""+dirPath+"\"" + "}"; + logger.info("request body: " + bodyStr); + + HttpResponseResult result = HttpUtil.sendPostRequestByJson(url, headers, bodyStr); + String respContent = result.getResultContent(); + + logger.info("NLP api respond: " + String.valueOf(result.getResultCode())); + logger.info(respContent); + + JSONObject map = JSON.parseObject(respContent); + + String status = map.getString("Status"); + logger.info("load result: " + status); + + return status; + } } diff --git a/server/src/main/resources/application.properties b/server/src/main/resources/application.properties index b27e3502..02bce6dc 100644 --- a/server/src/main/resources/application.properties +++ b/server/src/main/resources/application.properties @@ -17,7 +17,9 @@ server.servlet.contextPath=/api/usecaseui-server/v1 server.port=8082 spring.http.multipart.max-file-size=512MB +spring.servlet.multipart.max-file-size=512MB spring.http.multipart.max-request-size=512MB +spring.servlet.multipart.max-request-size=512MB ## App DB Properties spring.datasource.url=jdbc:postgresql://localhost:5432/uui diff --git a/server/src/test/java/org/onap/usecaseui/server/controller/IntentControllerTest.java b/server/src/test/java/org/onap/usecaseui/server/controller/IntentControllerTest.java index e82ed0af..2300e8e6 100644 --- a/server/src/test/java/org/onap/usecaseui/server/controller/IntentControllerTest.java +++ b/server/src/test/java/org/onap/usecaseui/server/controller/IntentControllerTest.java @@ -16,6 +16,7 @@ package org.onap.usecaseui.server.controller; import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.junit.Before; import org.junit.Test; @@ -29,10 +30,12 @@ import org.onap.usecaseui.server.bean.intent.IntentModel; import org.onap.usecaseui.server.service.intent.IntentInstanceService; import org.onap.usecaseui.server.service.intent.IntentService; import org.onap.usecaseui.server.util.HttpUtil; +import org.onap.usecaseui.server.util.UploadFileUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.api.support.membermodification.MemberModifier; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.File; @@ -46,12 +49,14 @@ import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.powermock.api.mockito.PowerMockito.*; +import static org.powermock.api.support.membermodification.MemberMatcher.method; @RunWith(PowerMockRunner.class) -@PrepareForTest({HttpUtil.class}) +@PrepareForTest({HttpUtil.class,UploadFileUtil.class}) public class IntentControllerTest { public IntentControllerTest(){} @@ -73,6 +78,40 @@ public class IntentControllerTest { } + @Test + public void uploadModelTest() throws Exception { + MultipartFile file=PowerMockito.mock(MultipartFile.class); + PowerMockito.when(file.getOriginalFilename()).thenReturn("filename.zip"); + IntentController spy = PowerMockito.spy(intentController); + File dest=PowerMockito.mock(File.class); + when(spy.newFile(anyString())).thenReturn(dest); + File parent=PowerMockito.mock(File.class); + when(dest.getParentFile()).thenReturn(parent); + when(parent.mkdirs()).thenReturn(true); + doNothing().when(file).transferTo(dest); + when(dest.length()).thenReturn(1024L); + PowerMockito.mockStatic(UploadFileUtil.class); + when(UploadFileUtil.formUpload(anyString(), any(Map.class), any(Map.class),anyString())).thenReturn("ok"); + when(intentService.addModel(any(IntentModel.class))).thenReturn("1"); + assertEquals(spy.uploadModel(file, "5gs"), "1"); + } + @Test + public void uploadModelTestThrowError() throws Exception { + MultipartFile file=PowerMockito.mock(MultipartFile.class); + PowerMockito.when(file.getOriginalFilename()).thenReturn("filename.zip"); + IntentController spy = PowerMockito.spy(intentController); + File dest=PowerMockito.mock(File.class); + when(spy.newFile(anyString())).thenReturn(dest); + File parent=PowerMockito.mock(File.class); + when(dest.getParentFile()).thenReturn(parent); + when(parent.mkdirs()).thenReturn(true); + doThrow(new RuntimeException()).when(file).transferTo(dest); + + assertEquals(spy.uploadModel(file, "5gs"), "0"); + + } + + @Test public void activeModelTest() { IntentModel model = new IntentModel(); @@ -98,11 +137,17 @@ public class IntentControllerTest { when(intentService.deleteModel(anyString())).thenReturn("1"); File file=PowerMockito.mock(File.class); - PowerMockito.whenNew(File.class).withArguments(Mockito.anyString()).thenReturn(file); + IntentController spy = PowerMockito.spy(intentController); + when(spy.newFile(anyString())).thenReturn(file); PowerMockito.when(file.exists()).thenReturn(true); PowerMockito.when(file.delete()).thenReturn(true); - assertEquals(intentController.deleteModel(modelId), "1"); + HttpResponseResult mock = PowerMockito.mock(HttpResponseResult.class); + PowerMockito.mockStatic(HttpUtil.class); + when(HttpUtil.sendGetRequest(anyString(), any(Map.class))).thenReturn(mock); + when(mock.getResultContent()).thenReturn("{}"); + + assertEquals(spy.deleteModel(modelId), "1"); } @@ -110,23 +155,67 @@ public class IntentControllerTest { public void predictTest() throws ParseException { Map body = new HashMap<>(); body.put("text", "text"); + body.put("modelType", "5gs"); String respContent = ""; HttpResponseResult mock = PowerMockito.mock(HttpResponseResult.class); PowerMockito.mockStatic(HttpUtil.class); Mockito.when(HttpUtil.sendPostRequestByJson(anyString(), any(Map.class), anyString())).thenReturn(mock); - when(mock.getResultContent()).thenReturn("{'Region':'chengnan'}"); + when(mock.getResultContent()).thenReturn("{'Area':'chengnan'}"); when(intentService.calcFieldValue(anyString(), anyString())).thenReturn("Beijing Changping District Chengnan Street"); - String predict = intentController.predict(body); - JSONObject jsonObject = JSON.parseObject(predict); + when(intentService.getActiveModelType()).thenReturn("5gs"); + Map predict = intentController.predict(body); + JSONObject jsonObject = new JSONObject(predict); assertEquals(jsonObject.getString("coverageArea"), "Beijing Changping District Chengnan Street"); } + @Test + public void unifyPredict_5gs_Test() throws ParseException { + Map body = new HashMap<>(); + body.put("text", "Service"); + String respContent = ""; + when(intentService.getModelTypeByIntentText(anyString())).thenReturn("5gs"); + when(intentService.getActiveModelType()).thenReturn("5gs"); + + HttpResponseResult mock = PowerMockito.mock(HttpResponseResult.class); + PowerMockito.mockStatic(HttpUtil.class); + Mockito.when(HttpUtil.sendPostRequestByJson(anyString(), any(Map.class), anyString())).thenReturn(mock); + when(mock.getResultContent()).thenReturn("{'Area':'chengnan'}"); + when(intentService.calcFieldValue(anyString(), anyString())).thenReturn("Beijing Changping District Chengnan Street"); + Map predict = intentController.unifyPredict(body); + JSONObject jsonObject = new JSONObject(predict); + + assertEquals(jsonObject.getString("type"), "5gs"); + assertEquals(jsonObject.getJSONObject("formData").getString("coverageArea"), "Beijing Changping District Chengnan Street"); + } + @Test + public void unifyPredict_ccvpn_Test() throws ParseException { + Map body = new HashMap<>(); + body.put("text", "I need create a Cloud Leased Line, I need a line from Access two to Cloud one, 20Gbps"); + String respContent = ""; + when(intentService.getModelTypeByIntentText(anyString())).thenReturn("ccvpn"); + when(intentService.getActiveModelType()).thenReturn("ccvpn"); + + HttpResponseResult mock = PowerMockito.mock(HttpResponseResult.class); + PowerMockito.mockStatic(HttpUtil.class); + Mockito.when(HttpUtil.sendPostRequestByJson(anyString(), any(Map.class), anyString())).thenReturn(mock); + when(mock.getResultContent()).thenReturn("{'access point':'','cloud point':'','bandwidth':''}"); + when(intentInstanceService.formatAccessPoint(anyString())).thenReturn(""); + when(intentInstanceService.formatCloudPoint(anyString())).thenReturn(""); + Map predict = intentController.unifyPredict(body); + JSONObject jsonObject = new JSONObject(predict); + + + assertEquals(jsonObject.getString("type"), "ccvpn"); + assertEquals(jsonObject.getJSONObject("formData").getJSONObject("accessPointOne").getString("name"), "tranportEp_src_ID_111_2"); + assertEquals(jsonObject.getJSONObject("formData").getString("cloudPointName"), "tranportEp_dst_ID_212_1"); + } + @Test public void tranlateFieldNameTest() throws InvocationTargetException, IllegalAccessException { - String key = "Region"; + String key = "Area"; IntentController spy = PowerMockito.spy(intentController); - Method method = PowerMockito.method(IntentController.class, "tranlateFieldName", String.class); + Method method = method(IntentController.class, "tranlateFieldName", String.class); Object result = method.invoke(spy, key); assertEquals(result, "coverageArea"); } @@ -200,4 +289,16 @@ public class IntentControllerTest { Mockito.when(intentInstanceService.queryAccessNodeInfo()).thenReturn("ok"); assertEquals(intentController.queryAccessNodeInfo(), "ok"); } + + @Test + public void getInstanceStatusTest() { + Map body = new HashMap<>(); + List ids = new ArrayList<>(); + ids.add("1"); + ids.add("2"); + ids.add("3"); + body.put("ids", ids); + when(intentInstanceService.getInstanceStatus(any(JSONArray.class))).thenReturn(new JSONObject()); + assertTrue(intentController.getInstanceStatus(body) instanceof JSONObject); + } } \ No newline at end of file diff --git a/server/src/test/java/org/onap/usecaseui/server/service/intent/impl/IntentInstanceServiceImplTest.java b/server/src/test/java/org/onap/usecaseui/server/service/intent/impl/IntentInstanceServiceImplTest.java index 8e591ea6..de7a58c8 100644 --- a/server/src/test/java/org/onap/usecaseui/server/service/intent/impl/IntentInstanceServiceImplTest.java +++ b/server/src/test/java/org/onap/usecaseui/server/service/intent/impl/IntentInstanceServiceImplTest.java @@ -17,11 +17,13 @@ package org.onap.usecaseui.server.service.intent.impl; import java.io.IOException; import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; +import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; +import okhttp3.MediaType; +import okhttp3.ResponseBody; +import okio.BufferedSource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; @@ -33,6 +35,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.onap.usecaseui.server.bean.intent.CCVPNInstance; +import org.onap.usecaseui.server.bean.intent.InstancePerformance; import org.onap.usecaseui.server.bean.intent.IntentModel; import org.onap.usecaseui.server.service.intent.IntentApiService; import org.onap.usecaseui.server.service.lcm.domain.so.SOService; @@ -43,14 +46,14 @@ import org.powermock.api.support.membermodification.MemberModifier; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.powermock.api.mockito.PowerMockito.doReturn; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.ArgumentMatchers.*; +import static org.powermock.api.mockito.PowerMockito.*; import retrofit2.Call; import retrofit2.Response; +import javax.annotation.Nullable; + @RunWith(PowerMockRunner.class) public class IntentInstanceServiceImplTest { @@ -80,7 +83,22 @@ public class IntentInstanceServiceImplTest { } @Test - public void queryIntentInstance() { + public void queryIntentInstanceTest() { + CCVPNInstance instance = new CCVPNInstance(); + instance.setInstanceId("1"); + instance.setJobId("1"); + instance.setStatus("1"); + + Query query = Mockito.mock(Query.class); + when(session.createQuery(anyString())).thenReturn(query); + List list = new ArrayList<>(); + when(query.list()).thenReturn(list); + when(query.uniqueResult()).thenReturn(10L); + assertTrue(intentInstanceService.queryIntentInstance(instance,1,2).getList().isEmpty()); + } + + @Test + public void queryIntentInstanceGetCountErrorTest() { CCVPNInstance instance = new CCVPNInstance(); instance.setInstanceId("1"); instance.setJobId("1"); @@ -93,8 +111,20 @@ public class IntentInstanceServiceImplTest { when(query.uniqueResult()).thenReturn(10); assertTrue(intentInstanceService.queryIntentInstance(instance,1,2).getList().isEmpty()); } + + @Test + public void queryIntentInstanceThrowErrorTest() { + CCVPNInstance instance = new CCVPNInstance(); + instance.setInstanceId("1"); + instance.setJobId("1"); + instance.setStatus("1"); + + when(session.createQuery(anyString())).thenThrow(new RuntimeException()); + + assertEquals(intentInstanceService.queryIntentInstance(instance,1,2), null); + } @Test - public void createIntentInstance() throws IOException { + public void createIntentInstanceTest() throws IOException { CCVPNInstance instance = new CCVPNInstance(); instance.setInstanceId("1"); instance.setJobId("1"); @@ -106,6 +136,84 @@ public class IntentInstanceServiceImplTest { Mockito.when(intentApiService.createIntentInstance(any())).thenReturn(mockCall); Mockito.when(mockCall.execute()).thenReturn(response); + IntentInstanceServiceImpl spy = PowerMockito.spy(intentInstanceService); + doNothing().when(spy).saveIntentInstanceToAAI(isNull(),any(CCVPNInstance.class)); + + Transaction tx = Mockito.mock(Transaction.class); + Mockito.when(session.beginTransaction()).thenReturn(tx); + Serializable save = Mockito.mock(Serializable.class); + Mockito.when(session.save(any())).thenReturn(save); + Mockito.doNothing().when(tx).commit(); + + assertEquals(spy.createIntentInstance(instance), 1); + } + + @Test + public void createIntentInstanceThrowErrorTest() throws IOException { + CCVPNInstance instance = new CCVPNInstance(); + instance.setInstanceId("1"); + instance.setJobId("1"); + instance.setStatus("1"); + + Call mockCall = PowerMockito.mock(Call.class); + JSONObject body = JSONObject.parseObject("{\"jobId\":\"123\"}"); + Response response = Response.success(body); + Mockito.when(intentApiService.createIntentInstance(any())).thenReturn(mockCall); + Mockito.when(mockCall.execute()).thenReturn(response); + + IntentInstanceServiceImpl spy = PowerMockito.spy(intentInstanceService); + doThrow(new RuntimeException()).when(spy).saveIntentInstanceToAAI(isNull(),any(CCVPNInstance.class)); + + Transaction tx = Mockito.mock(Transaction.class); + Mockito.when(session.beginTransaction()).thenReturn(tx); + Serializable save = Mockito.mock(Serializable.class); + Mockito.when(session.save(any())).thenReturn(save); + Mockito.doNothing().when(tx).commit(); + + assertEquals(spy.createIntentInstance(instance), 0); + } + + @Test + public void createIntentInstanceInstanceIsNullTest() throws IOException { + assertEquals(intentInstanceService.createIntentInstance(null), 0); + } + @Test + public void createIntentInstanceInstanceJobIdIsNullTest() throws IOException { + CCVPNInstance instance = new CCVPNInstance(); + instance.setInstanceId("1"); + instance.setStatus("1"); + assertEquals(intentInstanceService.createIntentInstance(instance), 0); + } + + @Test + public void getIntentInstanceProgressTest() throws IOException { + + Query query1 = Mockito.mock(Query.class); + when(session.createQuery("from CCVPNInstance where deleteState = 0 and status = '0'")).thenReturn(query1); + List q = new ArrayList<>(); + CCVPNInstance instance = new CCVPNInstance(); + instance.setInstanceId("1"); + instance.setResourceInstanceId("1"); + instance.setJobId("1"); + q.add(instance); + when(query1.list()).thenReturn(q); + + OperationProgressInformation operationProgressInformation = new OperationProgressInformation(); + OperationProgress operationProgress = new OperationProgress(); + operationProgress.setProgress(100); + operationProgressInformation.setOperationStatus(operationProgress); + + JSONObject jsonObject = new JSONObject(); + JSONObject operation = new JSONObject(); + operation.put("progress", 100); + jsonObject.put("operation", operation); + Call mockCall = PowerMockito.mock(Call.class); + Response response = Response.success(jsonObject); + Mockito.when(intentApiService.queryOperationProgress(anyString(),anyString())).thenReturn(mockCall); + Mockito.when(mockCall.execute()).thenReturn(response); + + IntentInstanceServiceImpl spy = PowerMockito.spy(intentInstanceService); + doNothing().when(spy).saveIntentInstanceToAAI(anyString(),any(CCVPNInstance.class)); Transaction tx = Mockito.mock(Transaction.class); Mockito.when(session.beginTransaction()).thenReturn(tx); @@ -113,16 +221,19 @@ public class IntentInstanceServiceImplTest { Mockito.when(session.save(any())).thenReturn(save); Mockito.doNothing().when(tx).commit(); - assertEquals(intentInstanceService.createIntentInstance(instance), 1); + spy.getIntentInstanceProgress(); + assertEquals(operation.getString("progress"),"100"); } @Test - public void getIntentInstanceProgress() throws IOException { + public void getIntentInstanceCreateStatusTest() throws IOException { Query query1 = Mockito.mock(Query.class); when(session.createQuery("from CCVPNInstance where deleteState = 0 and status = '0'")).thenReturn(query1); List q = new ArrayList<>(); CCVPNInstance instance = new CCVPNInstance(); instance.setInstanceId("1"); + instance.setResourceInstanceId("1"); + instance.setJobId("1"); q.add(instance); when(query1.list()).thenReturn(q); @@ -130,18 +241,25 @@ public class IntentInstanceServiceImplTest { OperationProgress operationProgress = new OperationProgress(); operationProgress.setProgress(100); operationProgressInformation.setOperationStatus(operationProgress); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("orchestration-status", "created"); Call mockCall = PowerMockito.mock(Call.class); - Response response = Response.success(operationProgressInformation); - Mockito.when(soService.queryOperationProgress(any(),any())).thenReturn(mockCall); + Response response = Response.success(jsonObject); + Mockito.when(intentApiService.getInstanceInfo(anyString())).thenReturn(mockCall); Mockito.when(mockCall.execute()).thenReturn(response); + IntentInstanceServiceImpl spy = PowerMockito.spy(intentInstanceService); + doNothing().when(spy).saveIntentInstanceToAAI(anyString(),any(CCVPNInstance.class)); + Transaction tx = Mockito.mock(Transaction.class); Mockito.when(session.beginTransaction()).thenReturn(tx); Serializable save = Mockito.mock(Serializable.class); Mockito.when(session.save(any())).thenReturn(save); Mockito.doNothing().when(tx).commit(); - intentInstanceService.getIntentInstanceProgress(); + spy.getIntentInstanceCreateStatus(); + assertEquals(jsonObject.getString("orchestration-status"),"created"); } @Test @@ -311,15 +429,78 @@ public class IntentInstanceServiceImplTest { Call mockCall = PowerMockito.mock(Call.class); when(intentApiService.deleteIntentInstance(any())).thenReturn(mockCall); - Mockito.when(mockCall.execute()).thenReturn(null); + when(mockCall.execute()).thenReturn(null); - Transaction tx = Mockito.mock(Transaction.class); - Mockito.when(session.beginTransaction()).thenReturn(tx); - Serializable save = Mockito.mock(Serializable.class); - Mockito.doNothing().when(session).delete(any()); - Mockito.doNothing().when(tx).commit(); + Transaction tx = PowerMockito.mock(Transaction.class); + when(session.beginTransaction()).thenReturn(tx); + Serializable save = PowerMockito.mock(Serializable.class); + doNothing().when(session).delete(any()); + doNothing().when(tx).commit(); + + IntentInstanceServiceImpl spy = spy(intentInstanceService); + doNothing().when(spy).deleteIntentInstanceToAAI(anyString()); - intentInstanceService.deleteIntentInstance("1"); + spy.deleteIntentInstance("1"); + } + + + @Test + public void invalidIntentInstanceTest() throws IOException { + CCVPNInstance instance = new CCVPNInstance(); + instance.setResourceInstanceId("1"); + + Query query = Mockito.mock(Query.class); + when(session.createQuery(anyString())).thenReturn(query); + when(query.setParameter(anyString(), anyString())).thenReturn(query); + when(query.uniqueResult()).thenReturn(instance); + + Call mockCall = PowerMockito.mock(Call.class); + when(intentApiService.deleteIntentInstance(any())).thenReturn(mockCall); + when(mockCall.execute()).thenReturn(null); + + Transaction tx = PowerMockito.mock(Transaction.class); + when(session.beginTransaction()).thenReturn(tx); + Serializable save = PowerMockito.mock(Serializable.class); + doNothing().when(session).delete(any()); + doNothing().when(tx).commit(); + + intentInstanceService.invalidIntentInstance("1"); + } + @Test + public void queryInstancePerformanceDataTest() throws IOException { + CCVPNInstance instance = new CCVPNInstance(); + instance.setResourceInstanceId("1"); + + InstancePerformance instancePerformance = new InstancePerformance(); + instancePerformance.setBandwidth(2000); + instancePerformance.setMaxBandwidth(20000); + instancePerformance.setDate(new Date()); + Object[] o = {null,instancePerformance}; + List queryResult= new ArrayList<>(); + queryResult.add(o); + + Query query = Mockito.mock(Query.class); + when(session.createQuery(anyString())).thenReturn(query); + when(query.setParameter(anyString(), anyString())).thenReturn(query); + when(query.list()).thenReturn(queryResult); + + intentInstanceService.queryInstancePerformanceData("1"); + + + + + + Call mockCall = PowerMockito.mock(Call.class); + when(intentApiService.deleteIntentInstance(any())).thenReturn(mockCall); + when(mockCall.execute()).thenReturn(null); + + Transaction tx = PowerMockito.mock(Transaction.class); + when(session.beginTransaction()).thenReturn(tx); + Serializable save = PowerMockito.mock(Serializable.class); + doNothing().when(session).delete(any()); + doNothing().when(tx).commit(); + + intentInstanceService.invalidIntentInstance("1"); } @Test @@ -355,11 +536,245 @@ public class IntentInstanceServiceImplTest { public void queryAccessNodeInfo() throws IOException { Call mockCall = PowerMockito.mock(Call.class); - JSONObject body = JSONObject.parseObject("{\"data\":[{\"type\":\"ROOT\",\"route-id\":\"route1\"},{\"type\":\"route\",\"route-id\":\"route2\"}]}"); + JSONObject body = JSONObject.parseObject("{\n" + + " \"network-route\": [\n" + + " {\n" + + " \"route-id\": \"tranportEp_src_ID_111_1\",\n" + + " \"type\": \"LEAF\",\n" + + " \"role\": \"3gppTransportEP\",\n" + + " \"function\": \"3gppTransportEP\",\n" + + " \"ip-address\": \"10.2.3.4\",\n" + + " \"prefix-length\": 24,\n" + + " \"next-hop\": \"networkId-providerId-10-clientId-0-topologyId-2-nodeId-10.1.1.1-ltpId-1000\",\n" + + " \"address-family\": \"ipv4\",\n" + + " \"resource-version\": \"1634198223345\"\n" + + " },\n" + + " {\n" + + " \"route-id\": \"tranportEp_src_ID_113_1\",\n" + + " \"type\": \"LEAF\",\n" + + " \"role\": \"3gppTransportEP\",\n" + + " \"function\": \"3gppTransportEP\",\n" + + " \"ip-address\": \"10.2.3.4\",\n" + + " \"prefix-length\": 24,\n" + + " \"next-hop\": \"networkId-providerId-10-clientId-0-topologyId-2-nodeId-10.1.1.3-ltpId-1000\",\n" + + " \"address-family\": \"ipv4\",\n" + + " \"resource-version\": \"1634198260496\"\n" + + " },\n" + + " {\n" + + " \"route-id\": \"tranportEp_src_ID_111_2\",\n" + + " \"type\": \"LEAF\",\n" + + " \"role\": \"3gppTransportEP\",\n" + + " \"function\": \"3gppTransportEP\",\n" + + " \"ip-address\": \"10.2.3.4\",\n" + + " \"prefix-length\": 24,\n" + + " \"next-hop\": \"networkId-providerId-10-clientId-0-topologyId-2-nodeId-10.1.1.1-ltpId-2000\",\n" + + " \"address-family\": \"ipv4\",\n" + + " \"resource-version\": \"1634198251534\"\n" + + " },\n" + + " {\n" + + " \"route-id\": \"tranportEp_dst_ID_212_1\",\n" + + " \"type\": \"ROOT\",\n" + + " \"role\": \"3gppTransportEP\",\n" + + " \"function\": \"3gppTransportEP\",\n" + + " \"ip-address\": \"10.2.3.4\",\n" + + " \"prefix-length\": 24,\n" + + " \"next-hop\": \"networkId-providerId-20-clientId-0-topologyId-2-nodeId-10.2.1.2-ltpId-512\",\n" + + " \"address-family\": \"ipv4\",\n" + + " \"resource-version\": \"1634198274852\"\n" + + " }\n" + + " ]\n" + + "}"); Response response = Response.success(body); Mockito.when(intentApiService.queryNetworkRoute()).thenReturn(mockCall); Mockito.when(mockCall.execute()).thenReturn(response); Map result = (Map) intentInstanceService.queryAccessNodeInfo(); - assertEquals(((List)result.get("accessNodeList")).size(), 1); + assertEquals(((List)result.get("accessNodeList")).size(), 3); + } + + @Test + public void getInstanceStatusTest() { + List queryResult = new ArrayList<>(); + CCVPNInstance instance = new CCVPNInstance(); + instance.setInstanceId("id1"); + instance.setStatus("1"); + queryResult.add(instance); + + Query query = Mockito.mock(Query.class); + when(session.createQuery(anyString())).thenReturn(query); + when(query.setParameter(anyString(), any())).thenReturn(query); + when(query.list()).thenReturn(queryResult); + + + JSONObject instanceStatus = intentInstanceService.getInstanceStatus(new JSONArray()); + assertEquals(instanceStatus.getJSONArray("IntentInstances").getJSONObject(0).getString("id"), "id1"); + } + @Test + public void formatBandwidthTest() { + + String bandwidth = intentInstanceService.formatBandwidth("2Gbps"); + assertEquals(bandwidth, "2000"); + } + @Test + public void formatCloudPointTest() { + + String bandwidth = intentInstanceService.formatCloudPoint("Cloud one"); + assertEquals(bandwidth, "tranportEp_dst_ID_212_1"); + } + @Test + public void formatAccessPointOneTest() { + String bandwidth = intentInstanceService.formatAccessPoint("Access one"); + assertEquals(bandwidth, "tranportEp_src_ID_111_1"); + } + @Test + public void formatAccessPointTwoTest() { + String bandwidth = intentInstanceService.formatAccessPoint("Access two"); + assertEquals(bandwidth, "tranportEp_src_ID_111_2"); + } + @Test + public void formatAccessPointThreeTest() { + String bandwidth = intentInstanceService.formatAccessPoint("Access three"); + assertEquals(bandwidth, "tranportEp_src_ID_113_1"); + } + + @Test + public void addCustomerTest() throws IOException { + + Call mockCall = PowerMockito.mock(Call.class); + Response response = Response.error(404, new ResponseBody() { + @Nullable + @Override + public MediaType contentType() { + return null; + } + + @Override + public long contentLength() { + return 0; + } + + @Override + public BufferedSource source() { + return null; + } + }); + when(intentApiService.queryCustomer(anyString())).thenReturn(mockCall); + when(mockCall.execute()).thenReturn(response); + + Properties properties = new Properties(); + properties.put("ccvpn.globalCustomerId", "IBNCustomer"); + properties.put("ccvpn.subscriberName", "IBNCustomer"); + properties.put("ccvpn.subscriberType", "INFRA"); + properties.put("ccvpn.serviceType", "IBN"); + IntentInstanceServiceImpl spy = spy(intentInstanceService); + doReturn(properties).when(spy).getProperties(); + + Call mockCall2 = PowerMockito.mock(Call.class); + when(intentApiService.addCustomer(anyString(),any())).thenReturn(mockCall2); + + spy.addCustomer(); + Mockito.verify(intentApiService,Mockito.times(1)).addCustomer(anyString(),any()); + } + + + @Test + public void addSubscriptionTest() throws IOException { + + Call mockCall = PowerMockito.mock(Call.class); + Response response = Response.error(404, new ResponseBody() { + @Nullable + @Override + public MediaType contentType() { + return null; + } + + @Override + public long contentLength() { + return 0; + } + + @Override + public BufferedSource source() { + return null; + } + }); + when(intentApiService.querySubscription(anyString(),anyString())).thenReturn(mockCall); + when(mockCall.execute()).thenReturn(response); + + Properties properties = new Properties(); + properties.put("ccvpn.globalCustomerId", "IBNCustomer"); + properties.put("ccvpn.subscriberName", "IBNCustomer"); + properties.put("ccvpn.subscriberType", "INFRA"); + properties.put("ccvpn.serviceType", "IBN"); + IntentInstanceServiceImpl spy = spy(intentInstanceService); + doReturn(properties).when(spy).getProperties(); + + Call mockCall2 = PowerMockito.mock(Call.class); + when(intentApiService.addSubscription(anyString(),anyString(),any())).thenReturn(mockCall2); + + spy.addSubscription(); + Mockito.verify(intentApiService,Mockito.times(1)).addSubscription(anyString(),anyString(),any()); + } + + @Test + public void saveIntentInstanceToAAITest() throws IOException { + IntentInstanceServiceImpl spy = spy(intentInstanceService); + doNothing().when(spy).addCustomer(); + doNothing().when(spy).addSubscription(); + + Properties properties = new Properties(); + properties.put("ccvpn.globalCustomerId", "IBNCustomer"); + properties.put("ccvpn.subscriberName", "IBNCustomer"); + properties.put("ccvpn.subscriberType", "INFRA"); + properties.put("ccvpn.serviceType", "IBN"); + doReturn(properties).when(spy).getProperties(); + + JSONObject body = new JSONObject(); + body.put("resource-version",123); + Call mockCall = PowerMockito.mock(Call.class); + Response response = Response.success(body); + when(intentApiService.queryServiceInstance(anyString(),anyString(),anyString())).thenReturn(mockCall); + when(mockCall.execute()).thenReturn(response); + + CCVPNInstance instance = new CCVPNInstance(); + instance.setName("name"); + instance.setInstanceId("id"); + + Call mockCall2 = PowerMockito.mock(Call.class); + Response response2 = Response.success(body); + when(intentApiService.saveServiceInstance(anyString(),anyString(),anyString(),any())).thenReturn(mockCall2); + when(mockCall2.execute()).thenReturn(response2); + + spy.saveIntentInstanceToAAI("CCVPN-id",instance); + Mockito.verify(intentApiService, Mockito.times(1)).saveServiceInstance(anyString(),anyString(),anyString(),any()); + + } + @Test + public void deleteIntentInstanceToAAITest() throws IOException { + IntentInstanceServiceImpl spy = spy(intentInstanceService); + doNothing().when(spy).addCustomer(); + doNothing().when(spy).addSubscription(); + + Properties properties = new Properties(); + properties.put("ccvpn.globalCustomerId", "IBNCustomer"); + properties.put("ccvpn.subscriberName", "IBNCustomer"); + properties.put("ccvpn.subscriberType", "INFRA"); + properties.put("ccvpn.serviceType", "IBN"); + doReturn(properties).when(spy).getProperties(); + + JSONObject body = new JSONObject(); + body.put("resource-version",123); + Call mockCall = PowerMockito.mock(Call.class); + Response response = Response.success(body); + when(intentApiService.queryServiceInstance(anyString(),anyString(),anyString())).thenReturn(mockCall); + when(mockCall.execute()).thenReturn(response); + + Call mockCall2 = PowerMockito.mock(Call.class); + Response response2 = Response.success(body); + when(intentApiService.deleteServiceInstance(anyString(),anyString(),anyString(),anyString())).thenReturn(mockCall2); + when(mockCall2.execute()).thenReturn(response2); + + spy.deleteIntentInstanceToAAI("CCVPN-id"); + Mockito.verify(intentApiService, Mockito.times(1)).deleteServiceInstance(anyString(),anyString(),anyString(),any()); + } } \ No newline at end of file diff --git a/server/src/test/java/org/onap/usecaseui/server/service/intent/impl/IntentServiceImplTest.java b/server/src/test/java/org/onap/usecaseui/server/service/intent/impl/IntentServiceImplTest.java index a228b769..991cae64 100644 --- a/server/src/test/java/org/onap/usecaseui/server/service/intent/impl/IntentServiceImplTest.java +++ b/server/src/test/java/org/onap/usecaseui/server/service/intent/impl/IntentServiceImplTest.java @@ -20,6 +20,7 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; +import java.util.Map; import org.hibernate.query.Query; import org.hibernate.Session; @@ -31,7 +32,10 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.onap.usecaseui.server.bean.HttpResponseResult; import org.onap.usecaseui.server.bean.intent.IntentModel; +import org.onap.usecaseui.server.constant.IntentConstant; +import org.onap.usecaseui.server.util.HttpUtil; import org.onap.usecaseui.server.util.ZipUtil; import org.powermock.api.mockito.PowerMockito; import org.powermock.api.support.membermodification.MemberModifier; @@ -39,15 +43,13 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.powermock.api.mockito.PowerMockito.doReturn; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.ArgumentMatchers.*; +import static org.powermock.api.mockito.PowerMockito.*; @RunWith(PowerMockRunner.class) -@PrepareForTest({ZipUtil.class}) -class IntentServiceImplTest { +@PrepareForTest({ZipUtil.class, HttpUtil.class}) +public class IntentServiceImplTest { public IntentServiceImplTest(){} @@ -94,7 +96,7 @@ class IntentServiceImplTest { public void getModel() { Query query = Mockito.mock(Query.class); when(session.createQuery(anyString())).thenReturn(query); - when(query.setParameter("modelId", "1")).thenReturn(query); + when(query.setParameter("modelId", 1)).thenReturn(query); when(query.uniqueResult()).thenReturn(null); assertEquals(intentService.getModel("1"), null); @@ -115,17 +117,24 @@ class IntentServiceImplTest { doReturn(tx).when(session,"beginTransaction"); Query query = Mockito.mock(Query.class); - when(session.createQuery(anyString())).thenReturn(query); + when(session.createQuery("from IntentModel where active=1")).thenReturn(query); List list = new ArrayList<>(); IntentModel intentModel = new IntentModel(); intentModel.setActive(1); list.add(intentModel); when(query.list()).thenReturn(list); + + Query query2 = Mockito.mock(Query.class); + when(session.createQuery("from IntentModel where id = :modelId")).thenReturn(query2); + when(query2.setParameter("modelId",1)).thenReturn(query2); + IntentModel intentModel2 = new IntentModel(); + intentModel2.setActive(0); + when(query2.uniqueResult()).thenReturn(intentModel2); Serializable save = Mockito.mock(Serializable.class); Mockito.when(session.save(any())).thenReturn(save); Mockito.doNothing().when(tx).commit(); - assertEquals(intentService.activeModel("1"), null); + assertEquals(intentService.activeModel("1"), intentModel2); } @Test @@ -137,6 +146,18 @@ class IntentServiceImplTest { IntentModel model = new IntentModel(); assertEquals(intentService.activeModelFile(model), null); } + @Test + public void activeModelFileFilePathIsZIPTest() { + IntentModel model = new IntentModel(); + model.setModelName("fileName.zip"); + + PowerMockito.mockStatic(HttpUtil.class); + HttpResponseResult mock = PowerMockito.mock(HttpResponseResult.class); + when(HttpUtil.sendGetRequest(anyString(),any(Map.class))).thenReturn(mock); + when(mock.getResultContent()).thenReturn("OK"); + + assertEquals(intentService.activeModelFile(model), "fileName"); + } @Test @@ -161,7 +182,7 @@ class IntentServiceImplTest { } @Test public void calcFieldValueKeyIsCoverageAreaTest() { - assertEquals(intentService.calcFieldValue("coverageArea", "zhongguancun"), "Beijing Haidian District Zhongguancun"); + assertEquals(intentService.calcFieldValue("coverageArea", "zhongguancun"), "Beijing;Beijing;Haidian District;Zhongguancun Street"); } @Test public void calcFieldValueKeyIsMaxNumberofUEsTest() { @@ -172,9 +193,33 @@ class IntentServiceImplTest { assertEquals(intentService.calcFieldValue("expDataRateDL", "1gb"), "1000"); } @Test + public void calcFieldValueKeyIsExpDataRateDLMBTest() { + assertEquals(intentService.calcFieldValue("expDataRateDL", "1mbpss"), "100"); + } + @Test + public void calcFieldValueKeyIsExpDataRateULTest() { + assertEquals(intentService.calcFieldValue("expDataRateUL", "1gb"), "1000"); + } + @Test + public void calcFieldValueKeyIsExpDataRateULMBTest() { + assertEquals(intentService.calcFieldValue("expDataRateUL", "1mbpss"), "100"); + } + @Test public void calcFieldValueKeyIsLatencyTest() { assertEquals(intentService.calcFieldValue("latency", "1s"), "200"); } + @Test + public void calcFieldValueKeyIsLatencyDefaultTest() { + assertEquals(intentService.calcFieldValue("latency", "default"), "200"); + } + @Test + public void calcFieldValueKeyIsLatencyLowTest() { + assertEquals(intentService.calcFieldValue("latency", "low"), "10"); + } + @Test + public void calcFieldValueKeyIsLatencyOtherTest() { + assertEquals(intentService.calcFieldValue("latency", "1min"), "200"); + } @Test @@ -185,4 +230,68 @@ class IntentServiceImplTest { Object result = method.invoke(spy, value); assertEquals(result, "shared"); } + + @Test + public void getActiveModelTypeTest() { + IntentModel intentModel = new IntentModel(); + intentModel.setModelType("ccvpn"); + Query query = PowerMockito.mock(Query.class); + when(session.createQuery(anyString())).thenReturn(query); + when(query.uniqueResult()).thenReturn(intentModel); + assertEquals(intentService.getActiveModelType(), "ccvpn"); + } + @Test + public void getActiveModelTypeThrowErrorTest() { + assertEquals(intentService.getActiveModelType(), null); + } + @Test + public void getModelTypeByIntentTextCCVPNTest() { + assertEquals(intentService.getModelTypeByIntentText("Cloud"), IntentConstant.MODEL_TYPE_CCVPN); + } + @Test + public void getModelTypeByIntentText5GSTest() { + assertEquals(intentService.getModelTypeByIntentText("5gs"), IntentConstant.MODEL_TYPE_5GS); + } + @Test + public void activeModelByTypeTest() { + Transaction tx = PowerMockito.mock(Transaction.class); + when(session.beginTransaction()).thenReturn(tx); + Query query = PowerMockito.mock(Query.class); + when(session.createQuery("from IntentModel where active=1")).thenReturn(query); + IntentModel intentModel = new IntentModel(); + intentModel.setActive(1); + List list = new ArrayList<>(); + list.add(intentModel); + when(query.list()).thenReturn(list); + Serializable save = PowerMockito.mock(Serializable.class); + when(session.save(intentModel)).thenReturn(save); + + Query query1 = PowerMockito.mock(Query.class); + when(session.createQuery("from IntentModel where modelType = :modelType order by createTime desc")).thenReturn(query1); + when(query1.setParameter("modelType", 1)).thenReturn(query1); + List list1 = new ArrayList<>(); + IntentModel intentModel1 = new IntentModel(); + intentModel1.setActive(0); + list1.add(intentModel1); + when(query1.list()).thenReturn(list1); + when(session.save(intentModel1)).thenReturn(save); + doNothing().when(tx).commit(); + + IntentServiceImpl spy = spy(intentService); + doReturn("fileName").when(spy).activeModelFile(intentModel1); + doReturn("OK").when(spy).load(anyString()); + + + assertEquals(spy.activeModelByType(IntentConstant.MODEL_TYPE_CCVPN), intentModel1); + } + @Test + public void loadTest() { + PowerMockito.mockStatic(HttpUtil.class); + HttpResponseResult result = PowerMockito.mock(HttpResponseResult.class); + when(HttpUtil.sendPostRequestByJson(anyString(), any(), anyString())).thenReturn(result); + when(result.getResultContent()).thenReturn("{\"Status\":\"OK\"}"); + assertEquals(intentService.load("filename"), "OK"); + + } + } \ No newline at end of file diff --git a/standalone/src/main/assembly/config/ccvpn.properties b/standalone/src/main/assembly/config/ccvpn.properties new file mode 100644 index 00000000..27288ee9 --- /dev/null +++ b/standalone/src/main/assembly/config/ccvpn.properties @@ -0,0 +1,21 @@ +## +## Copyright (C) 2019 CMCC, Inc. and others. All rights reserved. +## +## 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. +##/ + +ccvpn.globalCustomerId=IBNCustomer +ccvpn.subscriberName=IBNCustomer +ccvpn.subscriberType=INFRA +ccvpn.serviceType=IBN + diff --git a/standalone/src/main/assembly/resources/dbscripts/postgres/uui_create_table.sql b/standalone/src/main/assembly/resources/dbscripts/postgres/uui_create_table.sql index 6a3cf87c..d7201f51 100644 --- a/standalone/src/main/assembly/resources/dbscripts/postgres/uui_create_table.sql +++ b/standalone/src/main/assembly/resources/dbscripts/postgres/uui_create_table.sql @@ -170,7 +170,7 @@ DROP TABLE IF EXISTS ccvpn_instance; CREATE TABLE ccvpn_instance ( id serial not null - constraint intent_instance_pk + constraint ccvpn_instance_pk primary key, instance_id varchar(16), job_id varchar(36), @@ -182,7 +182,8 @@ CREATE TABLE ccvpn_instance access_point_one_name varchar(255), access_point_one_band_width integer, line_num varchar(64), - delete_state integer default 0 + delete_state integer default 0, + protect_status integer default 0 ); -- ---------------------------- -- cgit 1.2.3-korg