diff options
author | ’zhaoyh6‘ <zhaoyh6@asiainfo.com> | 2021-09-18 15:55:13 +0800 |
---|---|---|
committer | zhao yehua <zhaoyh6@asiainfo.com> | 2021-09-22 02:12:46 +0000 |
commit | bd772e79514f6a0109329d6feb7e99ba10d4b67a (patch) | |
tree | 2f0cb45b702baf9d8acee3472151ec746e8e078f | |
parent | c8aa12686a223fcc536eff31ec913cb7af8f3033 (diff) |
feat:Add file transfer function
Issue-ID: USECASEUI-605
Signed-off-by: zhaoyh6 <zhaoyh6@asiainfo.com>
Change-Id: Iae729bc56718839bad8c49408b0f50c020909765
12 files changed, 875 insertions, 112 deletions
diff --git a/server/src/main/java/org/onap/usecaseui/server/bean/intent/IntentInstance.java b/server/src/main/java/org/onap/usecaseui/server/bean/intent/IntentInstance.java index 521f28c5..8676821e 100644 --- a/server/src/main/java/org/onap/usecaseui/server/bean/intent/IntentInstance.java +++ b/server/src/main/java/org/onap/usecaseui/server/bean/intent/IntentInstance.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 CTC, Inc. and others. All rights reserved. + * Copyright (C) 2021 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. @@ -56,6 +56,9 @@ public class IntentInstance implements Serializable { @Column(name = "line_num") private String lineNum; + @Column(name = "delete_state") + private int deleteState; + public IntentInstance() { } @@ -147,4 +150,12 @@ public class IntentInstance implements Serializable { public void setLineNum(String lineNum) { this.lineNum = lineNum; } + + public int getDeleteState() { + return deleteState; + } + + public void setDeleteState(int deleteState) { + this.deleteState = deleteState; + } }
\ No newline at end of file diff --git a/server/src/main/java/org/onap/usecaseui/server/bean/intent/IntentModel.java b/server/src/main/java/org/onap/usecaseui/server/bean/intent/IntentModel.java index d8033bb7..1e21df25 100644 --- a/server/src/main/java/org/onap/usecaseui/server/bean/intent/IntentModel.java +++ b/server/src/main/java/org/onap/usecaseui/server/bean/intent/IntentModel.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 CTC, Inc. and others. All rights reserved. + * Copyright (C) 2021 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. @@ -47,6 +47,9 @@ public class IntentModel implements Serializable { @Column(name = "active") private Integer active; + @Column(name = "model_type") + private Integer modelType; + public IntentModel() { } @@ -98,4 +101,22 @@ public class IntentModel implements Serializable { public void setActive(Integer active) { this.active = active; } + + public String getModelType() { + if (this.modelType == 1) { + return "ccvpn"; + } + else { + return "5gs"; + } + } + + public void setModelType(String modelType) { + if ("ccvpn".equals(modelType)) { + this.modelType = 1; + } + else { + this.modelType = 0; + } + } }
\ No newline at end of file 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 428965cb..a1a2f206 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 @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 CTC, Inc. and others. All rights reserved. + * Copyright (C) 2021 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. @@ -23,13 +23,9 @@ import javax.annotation.Resource; import org.apache.commons.collections.MapUtils; import org.onap.usecaseui.server.bean.HttpResponseResult; -import org.onap.usecaseui.server.bean.csmf.SlicingOrder; -import org.onap.usecaseui.server.bean.csmf.SlicingOrderDetail; import org.onap.usecaseui.server.bean.intent.IntentInstance; import org.onap.usecaseui.server.bean.intent.IntentModel; import org.onap.usecaseui.server.bean.intent.IntentResponseBody; -import org.onap.usecaseui.server.bean.nsmf.common.ServiceResult; -import org.onap.usecaseui.server.controller.csmf.SlicingController; import org.onap.usecaseui.server.service.csmf.SlicingService; import org.onap.usecaseui.server.service.intent.IntentApiService; import org.onap.usecaseui.server.service.intent.IntentInstanceService; @@ -46,8 +42,6 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import retrofit2.Call; -import retrofit2.Response; @RestController @org.springframework.context.annotation.Configuration @@ -87,7 +81,7 @@ public class IntentController { @RequestMapping("/uploadModel") @ResponseBody - public String uploadModel (@RequestParam("file") MultipartFile file) { + public String uploadModel (@RequestParam("file") MultipartFile file,@RequestParam("modelType")String modelType) { String fileName = file.getOriginalFilename(); String filePath = UPLOADPATH + fileName ; @@ -110,6 +104,11 @@ public class IntentController { float sizeM = size/1024; model.setSize(sizeM); model.setActive(0); + model.setModelType(modelType); + Map<String,String> fileMap = new HashMap<>(); + fileMap.put("file", filePath); + UploadFileUtil.formUpload("http://uui-nlp:33013/uploader", null, fileMap, null); + intentService.addModel(model); logger.info("save model, " + model.toString()); @@ -134,14 +133,8 @@ public class IntentController { File dest = new File(filePath); if(dest.exists()){ dest.delete(); + postDeleteFile(fileName); logger.info("delete file OK: " + filePath); - if (filePath.endsWith(".zip")) { - String unzipPath = filePath.substring(0, filePath.length() - 1 - 4); - File unZipFile = new File(unzipPath); - if (unZipFile.exists()) { - unZipFile.delete(); - } - } }{ logger.info("file not found: " + filePath); } @@ -153,6 +146,21 @@ public class IntentController { return result; } + + private String postDeleteFile(String fileName) { + + String url = "http://uui-nlp:33013/deleteFile/"+ fileName; + HashMap<String, String> headers = new HashMap<>(); + + HttpResponseResult result = HttpUtil.sendGetRequest(url,headers); + String respContent = result.getResultContent(); + + logger.info("NLP api respond: " + String.valueOf(result.getResultCode())); + logger.info(respContent); + + return respContent; + } + @GetMapping(value = {"/activeModel"}, produces = "application/json") public String activeModel(@RequestParam String modelId){ String result = "0"; @@ -161,10 +169,9 @@ public class IntentController { IntentModel model = intentService.activeModel(modelId); logger.info("active NLP model, model=" + model.getFilePath()); - String dirPath = intentService.activeModelFile(model); - if (dirPath != null) { - dirPath = dirPath.replace(UPLOADPATH, NLPLOADPATH); - load(dirPath); + String fileName = intentService.activeModelFile(model); + if (fileName != null) { + load(NLPLOADPATH + fileName); } @@ -219,7 +226,12 @@ public class IntentController { produces = "application/json; charset=utf-8") public String predict(@RequestBody Object body) throws ParseException { String text = (String)((Map)body).get("text"); - //System.out.println(text); + String modelType = (String)((Map)body).get("modelType"); + + String activeModelType = intentService.getActiveModelType(); + if (modelType == null || !modelType.equals(activeModelType)) { + throw new RuntimeException("The active model file does not support parsing the current text"); + } String url = "http://uui-nlp.onap:33011/api/online/predict"; HashMap<String, String> headers = new HashMap<>(); @@ -277,7 +289,6 @@ public class IntentController { produces = "application/json") public JSONObject getInstanceId() { int first = new Random(10).nextInt(8) + 1; - System.out.println(first); int hashCodeV = UUID.randomUUID().toString().hashCode(); if (hashCodeV < 0) {//有可能是负数 hashCodeV = -hashCodeV; @@ -288,10 +299,14 @@ public class IntentController { return result; } @IntentResponseBody - @GetMapping(value = {"/getInstanceList/{currentPage}/{pageSize}"}, + @ResponseBody + @PostMapping (value = {"/getInstanceList"},consumes = MediaType.APPLICATION_JSON_VALUE, produces = "application/json") - public Object getInstanceList(@PathVariable String currentPage, @PathVariable String pageSize) { - return intentInstanceService.queryIntentInstance(null, Integer.parseInt(currentPage), Integer.parseInt(pageSize)); + public Object getInstanceList(@RequestBody Object body) { + int currentPage = (int) ((Map)body).get("currentPage"); + int pageSize = (int) ((Map)body).get("pageSize"); + logger.error("getInstanceList --> currentPage:" + currentPage + ",pageSize:" + pageSize); + return intentInstanceService.queryIntentInstance(null, currentPage, pageSize); } @IntentResponseBody @ResponseBody @@ -340,31 +355,39 @@ public class IntentController { } @IntentResponseBody - @DeleteMapping(value = {"/deleteIntentInstance"}, - produces = "application/json") - public Object deleteIntentInstance(@RequestParam(value = "instanceId") String instanceId) { + @ResponseBody + @PostMapping(value = {"/deleteIntentInstance"}, consumes = MediaType.APPLICATION_JSON_VALUE, + produces = "application/json; charset=utf-8") + public Object deleteIntentInstance(@RequestBody Object body) { + String instanceId= (String) ((Map)body).get("instanceId"); intentInstanceService.deleteIntentInstance(instanceId); return "ok"; } @IntentResponseBody - @PutMapping(value = {"/activeIntentInstance"}, - produces = "application/json") - public Object activeIntentInstance(@RequestParam(value = "instanceId") String instanceId) { + @ResponseBody + @PostMapping(value = {"/activeIntentInstance"}, consumes = MediaType.APPLICATION_JSON_VALUE, + produces = "application/json; charset=utf-8") + public Object activeIntentInstance(@RequestBody Object body) { + String instanceId= (String) ((Map)body).get("instanceId"); intentInstanceService.activeIntentInstance(instanceId); return "ok"; } @IntentResponseBody - @PutMapping(value = {"/invalidIntentInstance"}, - produces = "application/json") - public Object invalidIntentInstance(@RequestParam(value = "instanceId") String instanceId) { + @ResponseBody + @PostMapping(value = {"/invalidIntentInstance"}, consumes = MediaType.APPLICATION_JSON_VALUE, + produces = "application/json; charset=utf-8") + public Object invalidIntentInstance(@RequestBody Object body) { + String instanceId= (String) ((Map)body).get("instanceId"); intentInstanceService.invalidIntentInstance(instanceId); return "ok"; } @IntentResponseBody - @PutMapping(value = {"/queryInstancePerformanceData"}, - produces = "application/json") - public Object queryInstancePerformanceData(@RequestParam(value = "instanceId") String instanceId) { + @ResponseBody + @PostMapping(value = {"/queryInstancePerformanceData"}, consumes = MediaType.APPLICATION_JSON_VALUE, + produces = "application/json; charset=utf-8") + public Object queryInstancePerformanceData(@RequestBody Object body) { + String instanceId= (String) ((Map)body).get("instanceId"); return intentInstanceService.queryInstancePerformanceData(instanceId); } 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 d1d2848b..dcc6a2da 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 @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 CTC, Inc. and others. All rights reserved. + * Copyright (C) 2021 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. @@ -20,11 +20,12 @@ import java.util.List; import org.onap.usecaseui.server.bean.intent.IntentModel; public interface IntentService { - public String addModel(IntentModel model); + String addModel(IntentModel model); List<IntentModel> listModels(); - public String deleteModel(String modelId); - public IntentModel getModel(String modelId); - public IntentModel activeModel(String modelId); + String deleteModel(String modelId); + IntentModel getModel(String modelId); + IntentModel activeModel(String modelId); String activeModelFile(IntentModel model); String calcFieldValue(String key, String strValue); + String getActiveModelType(); } 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 d62150df..1abd2515 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 @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 CTC, Inc. and others. All rights reserved. + * Copyright (C) 2021 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. @@ -77,7 +77,7 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { int offset = page.countOffset(currentPage, pageSize); Session session = getSession(); try{ - StringBuffer hql =new StringBuffer("from IntentInstance a where 1=1"); + StringBuffer hql =new StringBuffer("from IntentInstance a where deleteState = 0"); if (null != intentInstance) { if(UuiCommonUtil.isNotNullOrEmpty(intentInstance.getInstanceId())) { String ver =intentInstance.getInstanceId(); @@ -113,7 +113,7 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { public int getAllCount(IntentInstance intentInstance,int currentPage,int pageSize) { Session session = getSession(); try{ - StringBuffer count=new StringBuffer("select count(*) from IntentInstance a where 1=1"); + StringBuffer count=new StringBuffer("select count(*) from IntentInstance a where deleteState = 0"); if (null != intentInstance) { if(UuiCommonUtil.isNotNullOrEmpty(intentInstance.getInstanceId())) { String ver =intentInstance.getInstanceId(); @@ -128,7 +128,6 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { count.append(" and a.status = '"+ver+"'"); } } - count.append(" order by id"); Query query = session.createQuery(count.toString()); long q=(long)query.uniqueResult(); return (int)q; @@ -248,7 +247,7 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { private List<IntentInstance> getInstanceByFinishedFlag(String flag) { Session session = getSession(); try{ - StringBuffer sql=new StringBuffer("from IntentInstance where status = '" + flag + "'"); + StringBuffer sql=new StringBuffer("from IntentInstance where deleteState = 0 and status = '" + flag + "'"); Query query = session.createQuery(sql.toString()); List<IntentInstance> q=(List<IntentInstance>) query.list(); @@ -265,7 +264,7 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { public List<IntentInstance> getFinishedInstanceInfo() { Session session = getSession(); try{ - StringBuffer count=new StringBuffer("from IntentInstance where status = '1'"); + StringBuffer count=new StringBuffer("from IntentInstance where status = '1' and deleteState = 0"); Query query = session.createQuery(count.toString()); List<IntentInstance> q=(List<IntentInstance>) query.list(); @@ -334,7 +333,7 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { try(Session session = getSession()) { - result = (IntentInstance)session.createQuery("from IntentInstance where instanceId = :instanceId") + result = (IntentInstance)session.createQuery("from IntentInstance where deleteState = 0 and instanceId = :instanceId") .setParameter("instanceId", instanceId).uniqueResult(); logger.info("get IntentInstance OK, id=" + instanceId); @@ -396,7 +395,7 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { try(Session session = getSession()) { - instance = (IntentInstance)session.createQuery("from IntentInstance where instanceId = :instanceId and status = :status") + instance = (IntentInstance)session.createQuery("from IntentInstance where deleteState = 0 and instanceId = :instanceId and status = :status") .setParameter("instanceId", instanceId).setParameter("status", "3").uniqueResult(); logger.info("get instance OK, id=" + instanceId); @@ -426,7 +425,7 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { IntentInstance instance = null; try(Session session = getSession()) { - instance = (IntentInstance)session.createQuery("from IntentInstance where instanceId = :instanceId") + instance = (IntentInstance)session.createQuery("from IntentInstance where deleteState = 0 and instanceId = :instanceId") .setParameter("instanceId", instanceId).uniqueResult(); logger.info("get instance OK, id=" + instanceId); @@ -454,8 +453,8 @@ public class IntentInstanceServiceImpl implements IntentInstanceService { @Override public Map<String, Object> queryInstancePerformanceData(String instanceId) { try(Session session = getSession()) { - String hql = "from IntentInstance i, InstancePerformance p where i.resourceInstanceId = p.resourceInstanceId order by p.date"; - Query query = session.createQuery(hql); + String hql = "from IntentInstance i, InstancePerformance p where i.resourceInstanceId = p.resourceInstanceId and i.instanceId = :instanceId and i.deleteState = 0 order by p.date"; + Query query = session.createQuery(hql).setParameter("instanceId", instanceId); List<Object[]> queryResult= query.list(); List<String> date = new ArrayList<>(); List<String> bandwidth = new ArrayList<>(); 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 1f08f15c..c2994db5 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 @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 CTC, Inc. and others. All rights reserved. + * Copyright (C) 2021 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. @@ -15,7 +15,6 @@ */ package org.onap.usecaseui.server.service.intent.impl; -import java.io.File; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -29,9 +28,10 @@ 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.IntentModel; import org.onap.usecaseui.server.service.intent.IntentService; -import org.onap.usecaseui.server.util.ZipUtil; +import org.onap.usecaseui.server.util.HttpUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -45,8 +45,6 @@ import org.springframework.stereotype.Service; public class IntentServiceImpl implements IntentService { private static final Logger logger = LoggerFactory.getLogger(IntentServiceImpl.class); - private final static String UPLOADPATH = "/home/uui/upload/"; - @Autowired private SessionFactory sessionFactory; @@ -101,12 +99,9 @@ public class IntentServiceImpl implements IntentService { } public IntentModel getModel(String modelId){ - //Transaction tx = null; IntentModel result = null; try(Session session = getSession()) { - //tx = session.beginTransaction(); - result = (IntentModel)session.createQuery("from IntentModel where id = :modelId") .setParameter("modelId", Integer.parseInt(modelId)).uniqueResult(); logger.info("get model OK, id=" + modelId); @@ -184,27 +179,35 @@ public class IntentServiceImpl implements IntentService { if (model == null) { return null; } - String filePath = model.getFilePath(); - if (filePath == null) { + String fileName = model.getModelName(); + if (fileName == null) { return null; } - else if (filePath.endsWith(".zip")){ + else if (fileName.endsWith(".zip")){ try { - File file = new File(filePath); - String parentPath = file.getParent(); - String unzipPath = filePath.substring(0, filePath.length() - 4); - File unZipFile = new File(unzipPath); - if (!unZipFile.exists()) { - ZipUtil.unzip(file,parentPath); - } - return unzipPath; + postUnzipFile(fileName); + return fileName; } catch (Exception e) { e.printStackTrace(); } } - return filePath; + return fileName; + } + + private String postUnzipFile(String fileName) { + + String url = "http://uui-nlp:33013/unzipFile/"+ fileName; + HashMap<String, String> headers = new HashMap<>(); + + HttpResponseResult result = HttpUtil.sendGetRequest(url,headers); + String respContent = result.getResultContent(); + + logger.info("NLP api respond: " + String.valueOf(result.getResultCode())); + logger.info(respContent); + + return respContent; } public String calcFieldValue(String key, String strValue){ @@ -386,4 +389,15 @@ public class IntentServiceImpl implements IntentService { } return ret; } + + + public String getActiveModelType() { + try(Session session = getSession()){ + IntentModel model = (IntentModel) session.createQuery("from IntentModel where active = 1").uniqueResult(); + return model.getModelType(); + } catch (Exception e) { + logger.error("Details:" + e.getMessage()); + return null; + } + } } diff --git a/server/src/main/java/org/onap/usecaseui/server/util/HttpUtil.java b/server/src/main/java/org/onap/usecaseui/server/util/HttpUtil.java index f1714b65..171ea28c 100644 --- a/server/src/main/java/org/onap/usecaseui/server/util/HttpUtil.java +++ b/server/src/main/java/org/onap/usecaseui/server/util/HttpUtil.java @@ -148,7 +148,7 @@ public class HttpUtil { * @param headerMap * @return HttpResponseResult */ - public HttpResponseResult sendGetRequest( + public static HttpResponseResult sendGetRequest( String url, Map<String, String> headerMap) { logger.info(LOG_FORMATTER ,url , "API GET calling is starting......"); diff --git a/server/src/main/java/org/onap/usecaseui/server/util/UploadFileUtil.java b/server/src/main/java/org/onap/usecaseui/server/util/UploadFileUtil.java new file mode 100644 index 00000000..361612e5 --- /dev/null +++ b/server/src/main/java/org/onap/usecaseui/server/util/UploadFileUtil.java @@ -0,0 +1,133 @@ +/* + * Copyright (C) 2021 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.util; + +import javax.activation.MimetypesFileTypeMap; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Iterator; +import java.util.Map; + +public class UploadFileUtil { + /** + * upload file + * @param urlStr + * @param textMap + * @param fileMap + * @param contentType default application/octet-stream + * @return return response data + */ + @SuppressWarnings("rawtypes") + public static String formUpload(String urlStr, Map<String, String> textMap, + Map<String, String> fileMap,String contentType) { + String res = ""; + HttpURLConnection conn = null; + String BOUNDARY = "---------------------------123821742118716"; + try { + URL url = new URL(urlStr); + conn = (HttpURLConnection) url.openConnection(); + conn.setConnectTimeout(5000); + conn.setReadTimeout(30000); + conn.setDoOutput(true); + conn.setDoInput(true); + conn.setUseCaches(false); + conn.setRequestMethod("POST"); + conn.setRequestProperty("Connection", "Keep-Alive"); + conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY); + OutputStream out = new DataOutputStream(conn.getOutputStream()); + if (textMap != null) { + StringBuffer strBuf = new StringBuffer(); + Iterator iter = textMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = (Map.Entry) iter.next(); + String inputName = (String) entry.getKey(); + String inputValue = (String) entry.getValue(); + if (inputValue == null) { + continue; + } + strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); + strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n"); + strBuf.append(inputValue); + } + out.write(strBuf.toString().getBytes()); + } + if (fileMap != null) { + Iterator iter = fileMap.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = (Map.Entry) iter.next(); + String inputName = (String) entry.getKey(); + String inputValue = (String) entry.getValue(); + if (inputValue == null) { + continue; + } + File file = new File(inputValue); + String filename = file.getName(); + + contentType = new MimetypesFileTypeMap().getContentType(file); + if(!"".equals(contentType)){ + if (filename.endsWith(".png")) { + contentType = "image/png"; + }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) { + contentType = "image/jpeg"; + }else if (filename.endsWith(".gif")) { + contentType = "image/gif"; + }else if (filename.endsWith(".ico")) { + contentType = "image/image/x-icon"; + } + } + if (contentType == null || "".equals(contentType)) { + contentType = "application/octet-stream"; + } + StringBuffer strBuf = new StringBuffer(); + strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); + strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n"); + strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); + out.write(strBuf.toString().getBytes()); + DataInputStream in = new DataInputStream(new FileInputStream(file)); + int bytes = 0; + byte[] bufferOut = new byte[1024]; + while ((bytes = in.read(bufferOut)) != -1) { + out.write(bufferOut, 0, bytes); + } + in.close(); + } + } + byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); + out.write(endData); + out.flush(); + out.close(); + StringBuffer strBuf = new StringBuffer(); + BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line = null; + while ((line = reader.readLine()) != null) { + strBuf.append(line).append("\n"); + } + res = strBuf.toString(); + reader.close(); + reader = null; + } catch (Exception e) { + System.out.println("Error sending post request:" + urlStr); + e.printStackTrace(); + } finally { + if (conn != null) { + conn.disconnect(); + conn = null; + } + } + return res; + } +} 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 a80574d5..7727420a 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 @@ -1,5 +1,5 @@ /* - * Copyright (C) 2017 CTC, Inc. and others. All rights reserved. + * Copyright (C) 2021 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. @@ -15,39 +15,44 @@ */ package org.onap.usecaseui.server.controller; -import static org.junit.Assert.assertEquals; -import static org.junit.jupiter.api.Assertions.*; - -import java.io.File; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.text.ParseException; -import java.util.HashMap; -import java.util.Map; - +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import org.junit.Before; import org.junit.Test; 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.IntentInstance; 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.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 com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; +import javax.annotation.Resource; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) @PrepareForTest({HttpUtil.class}) -class IntentControllerTest { +public class IntentControllerTest { public IntentControllerTest(){} @@ -55,8 +60,19 @@ class IntentControllerTest { private IntentController intentController; @Mock + @Resource(name = "IntentService") private IntentService intentService; + @Mock + private IntentInstanceService intentInstanceService; + + @Before + public void before() throws IllegalAccessException { + MemberModifier.field(IntentController.class, "intentService").set(intentController , intentService); + MemberModifier.field(IntentController.class, "intentInstanceService").set(intentController , intentInstanceService); + + } + @Test public void activeModelTest() { IntentModel model = new IntentModel(); @@ -110,8 +126,78 @@ class IntentControllerTest { public void tranlateFieldNameTest() throws InvocationTargetException, IllegalAccessException { String key = "Region"; IntentController spy = PowerMockito.spy(intentController); - Method method = PowerMockito.method(IntentController.class, "tranlateFieldName", String.class);//如果多个参数,逗号分隔,然后写参数类型.class + Method method = PowerMockito.method(IntentController.class, "tranlateFieldName", String.class); Object result = method.invoke(spy, key); assertEquals(result, "coverageArea"); } + @Test + public void getInstanceId() { + assertEquals(intentController.getInstanceId().containsKey("instanceId"), true); + } + @Test + public void getInstanceList() { + Map<String, Object> body = new HashMap<>(); + + body.put("currentPage",1); + body.put("pageSize",2); + Mockito.when(intentInstanceService.queryIntentInstance(null,1,2)).thenReturn(null); + assertEquals(intentController.getInstanceList(body), null); + } + @Test + public void createIntentInstance() throws IOException { + Map<String, Object> body = new HashMap<>(); + body.put("instanceId","instanceId"); + body.put("name","name"); + body.put("lineNum","lineNum"); + body.put("cloudPointName","cloudPointName"); + Map<String, Object> accessPointOne = new HashMap<>(); + accessPointOne.put("name","name"); + accessPointOne.put("bandwidth","1"); + body.put("accessPointOne",accessPointOne); + Mockito.when(intentInstanceService.createIntentInstance(any())).thenReturn(1); + assertEquals(intentController.createIntentInstance(body), "OK"); + } + @Test + public void getFinishedInstanceInfo() { + List<IntentInstance> instanceList = new ArrayList<>(); + IntentInstance instance = new IntentInstance(); + instance.setInstanceId("instanceId"); + instance.setName("name"); + instanceList.add(instance); + Mockito.when(intentInstanceService.getFinishedInstanceInfo()).thenReturn(instanceList); + assertEquals(((List)intentController.getFinishedInstanceInfo()).size(), 1); + } + @Test + public void deleteIntentInstance() { + Map<String, Object> body = new HashMap<>(); + body.put("instanceId", "instanceId"); + Mockito.doNothing().when(intentInstanceService).deleteIntentInstance(anyString()); + assertEquals(intentController.deleteIntentInstance(body), "ok"); + } + @Test + public void activeIntentInstance() { + Map<String, Object> body = new HashMap<>(); + body.put("instanceId", "instanceId"); + Mockito.doNothing().when(intentInstanceService).activeIntentInstance(anyString()); + assertEquals(intentController.activeIntentInstance(body), "ok"); + } + @Test + public void invalidIntentInstance() { + Map<String, Object> body = new HashMap<>(); + body.put("instanceId", "instanceId"); + Mockito.doNothing().when(intentInstanceService).invalidIntentInstance(anyString()); + assertEquals(intentController.invalidIntentInstance(body), "ok"); + } + @Test + public void queryInstancePerformanceData() { + Map<String, Object> body = new HashMap<>(); + body.put("instanceId", "instanceId"); + Mockito.when(intentInstanceService.queryInstancePerformanceData(anyString())).thenReturn(body); + assertEquals(intentController.queryInstancePerformanceData(body), body); + } + @Test + public void queryAccessNodeInfoTest() throws IOException { + Mockito.when(intentInstanceService.queryAccessNodeInfo()).thenReturn("ok"); + assertEquals(intentController.queryAccessNodeInfo(), "ok"); + } }
\ 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 new file mode 100644 index 00000000..372e0e15 --- /dev/null +++ b/server/src/test/java/org/onap/usecaseui/server/service/intent/impl/IntentInstanceServiceImplTest.java @@ -0,0 +1,367 @@ +/* + * Copyright (C) 2021 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.service.intent.impl; + +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.alibaba.fastjson.JSONObject; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.query.Query; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.usecaseui.server.bean.intent.IntentInstance; +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; +import org.onap.usecaseui.server.service.lcm.domain.so.bean.OperationProgress; +import org.onap.usecaseui.server.service.lcm.domain.so.bean.OperationProgressInformation; +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 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 retrofit2.Call; +import retrofit2.Response; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({IntentInstanceServiceImpl.class}) +public class IntentInstanceServiceImplTest { + + public IntentInstanceServiceImplTest() { + } + + @InjectMocks + private IntentInstanceServiceImpl intentInstanceService; + + @Mock + private IntentApiService intentApiService; + + @Mock + private SOService soService; + + + @Mock + private SessionFactory sessionFactory; + + @Mock + private Session session; + + @Before + public void before() throws Exception { + MemberModifier.field(IntentInstanceServiceImpl.class, "sessionFactory").set(intentInstanceService , sessionFactory); + doReturn(session).when(sessionFactory,"openSession"); + } + + @Test + public void queryIntentInstance() { + IntentInstance instance = new IntentInstance(); + instance.setInstanceId("1"); + instance.setJobId("1"); + instance.setStatus("1"); + + Query query = Mockito.mock(Query.class); + when(session.createQuery(anyString())).thenReturn(query); + List<IntentModel> list = new ArrayList<>(); + when(query.list()).thenReturn(list); + when(query.uniqueResult()).thenReturn(10); + assertTrue(intentInstanceService.queryIntentInstance(instance,1,2).getList().isEmpty()); + } + @Test + public void createIntentInstance() throws IOException { + IntentInstance instance = new IntentInstance(); + instance.setInstanceId("1"); + instance.setJobId("1"); + instance.setStatus("1"); + + Call mockCall = PowerMockito.mock(Call.class); + JSONObject body = JSONObject.parseObject("{\"jobId\":\"123\"}"); + Response<JSONObject> response = Response.success(body); + Mockito.when(intentApiService.createIntentInstance(any())).thenReturn(mockCall); + Mockito.when(mockCall.execute()).thenReturn(response); + + + 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(intentInstanceService.createIntentInstance(instance), 1); + } + @Test + public void getIntentInstanceProgress() throws IOException { + + Query query1 = Mockito.mock(Query.class); + when(session.createQuery("from IntentInstance where deleteState = 0 and status = '0'")).thenReturn(query1); + List<IntentInstance> q = new ArrayList<>(); + IntentInstance instance = new IntentInstance(); + instance.setInstanceId("1"); + q.add(instance); + when(query1.list()).thenReturn(q); + + OperationProgressInformation operationProgressInformation = new OperationProgressInformation(); + OperationProgress operationProgress = new OperationProgress(); + operationProgress.setProgress(100); + operationProgressInformation.setOperationStatus(operationProgress); + Call mockCall = PowerMockito.mock(Call.class); + Response<OperationProgressInformation> response = Response.success(operationProgressInformation); + Mockito.when(soService.queryOperationProgress(any(),any())).thenReturn(mockCall); + Mockito.when(mockCall.execute()).thenReturn(response); + + 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(); + } + + @Test + public void getFinishedInstanceInfo() { + Query query = Mockito.mock(Query.class); + when(session.createQuery(anyString())).thenReturn(query); + when(query.list()).thenReturn(new ArrayList()); + assertTrue(intentInstanceService.getFinishedInstanceInfo().isEmpty()); + } + + @Test + public void getIntentInstanceBandwidth() throws IOException { + Query query1 = Mockito.mock(Query.class); + when(session.createQuery("from IntentInstance where deleteState = 0 and status = '1'")).thenReturn(query1); + List<IntentInstance> q = new ArrayList<>(); + IntentInstance instance = new IntentInstance(); + instance.setInstanceId("1"); + instance.setResourceInstanceId("1"); + q.add(instance); + when(query1.list()).thenReturn(q); + + Call mockCall = PowerMockito.mock(Call.class); + JSONObject jsonObject = JSONObject.parseObject("{\n" + + " \"service-instance-id\":\"cll-101\",\n" + + " \"service-instance-name\":\"cloud-leased-line-101\",\n" + + " \"service-type\":\"CLL\",\n" + + " \"service-role\":\"cll\",\n" + + " \"environment-context\":\"cll\",\n" + + " \"model-invariant-id\":\"6790ab0e-034f-11eb-adc1-0242ac120002\",\n" + + " \"model-version-id\":\"6790ab0e-034f-11eb-adc1-0242ac120002\",\n" + + " \"resource-version\":\"1628714665927\",\n" + + " \"orchestration-status\":\"created\",\n" + + " \"allotted-resources\":{\n" + + " \"allotted-resource\":[\n" + + " {\n" + + " \"id\":\"cll-101-network-001\",\n" + + " \"resource-version\":\"1628714665798\",\n" + + " \"type\":\"TsciNetwork\",\n" + + " \"allotted-resource-name\":\"network_cll-101-network-001\",\n" + + " \"relationship-list\":{\n" + + " \"relationship\":[\n" + + " {\n" + + " \"related-to\":\"logical-link\",\n" + + " \"relationship-label\":\"org.onap.relationships.inventory.ComposedOf\",\n" + + " \"related-link\":\"/aai/v24/network/logical-links/logical-link/tranportEp_UNI_ID_311_1\",\n" + + " \"relationship-data\":[\n" + + " {\n" + + " \"relationship-key\":\"logical-link.link-name\",\n" + + " \"relationship-value\":\"tranportEp_UNI_ID_311_1\"\n" + + " }\n" + + " ]\n" + + " },\n" + + " {\n" + + " \"related-to\":\"network-policy\",\n" + + " \"relationship-label\":\"org.onap.relationships.inventory.Uses\",\n" + + " \"related-link\":\"/aai/v24/network/network-policies/network-policy/de00a0a0-be2e-4d19-974a-80a2bca6bdf9\",\n" + + " \"relationship-data\":[\n" + + " {\n" + + " \"relationship-key\":\"network-policy.network-policy-id\",\n" + + " \"relationship-value\":\"de00a0a0-be2e-4d19-974a-80a2bca6bdf9\"\n" + + " }\n" + + " ],\n" + + " \"related-to-property\":[\n" + + " {\n" + + " \"property-key\":\"network-policy.network-policy-fqdn\",\n" + + " \"property-value\":\"cll-101\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + " ]\n" + + " }\n" + + "}"); + Response<JSONObject> response = Response.success(jsonObject); + Mockito.when(intentApiService.getInstanceNetworkInfo(any())).thenReturn(mockCall); + Mockito.when(mockCall.execute()).thenReturn(response); + + Call mockCall1 = PowerMockito.mock(Call.class); + JSONObject jsonObject1 = JSONObject.parseObject("{\n" + + " \"network-policy-id\":\"de00a0a0-be2e-4d19-974a-80a2bca6bdf9\",\n" + + " \"network-policy-fqdn\":\"cll-101\",\n" + + " \"resource-version\":\"1628714665619\",\n" + + " \"name\":\"TSCi policy\",\n" + + " \"type\":\"SLA\",\n" + + " \"latency\":2,\n" + + " \"max-bandwidth\":3000,\n" + + " \"relationship-list\":{\n" + + " \"relationship\":[\n" + + " {\n" + + " \"related-to\":\"allotted-resource\",\n" + + " \"relationship-label\":\"org.onap.relationships.inventory.Uses\",\n" + + " \"related-link\":\"/aai/v24/business/customers/customer/IBNCustomer/service-subscriptions/service-subscription/IBN/service-instances/service-instance/cll-101/allotted-resources/allotted-resource/cll-101-network-001\",\n" + + " \"relationship-data\":[\n" + + " {\n" + + " \"relationship-key\":\"customer.global-customer-id\",\n" + + " \"relationship-value\":\"IBNCustomer\"\n" + + " },\n" + + " {\n" + + " \"relationship-key\":\"service-subscription.service-type\",\n" + + " \"relationship-value\":\"IBN\"\n" + + " },\n" + + " {\n" + + " \"relationship-key\":\"service-instance.service-instance-id\",\n" + + " \"relationship-value\":\"cll-101\"\n" + + " },\n" + + " {\n" + + " \"relationship-key\":\"allotted-resource.id\",\n" + + " \"relationship-value\":\"cll-101-network-001\"\n" + + " }\n" + + " ],\n" + + " \"related-to-property\":[\n" + + " {\n" + + " \"property-key\":\"allotted-resource.description\"\n" + + " },\n" + + " {\n" + + " \"property-key\":\"allotted-resource.allotted-resource-name\",\n" + + " \"property-value\":\"network_cll-101-network-001\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ]\n" + + " }\n" + + "}"); + Response<JSONObject> response1 = Response.success(jsonObject1); + Mockito.when(intentApiService.getInstanceNetworkPolicyInfo(any())).thenReturn(mockCall1); + Mockito.when(mockCall1.execute()).thenReturn(response1); + + Call mockCall2 = PowerMockito.mock(Call.class); + JSONObject jsonObject2 = JSONObject.parseObject("{\n" + + " \"metadatum\":[\n" + + " {\n" + + " \"metaname\":\"ethernet-uni-id-1\",\n" + + " \"metaval\":\"1234\",\n" + + " \"resource-version\":\"1629409084707\"\n" + + " },\n" + + " {\n" + + " \"metaname\":\"ethernet-uni-id-2\",\n" + + " \"metaval\":\"5678\",\n" + + " \"resource-version\":\"1629409204904\"\n" + + " }\n" + + " ]\n" + + "}"); + Response<JSONObject> response2 = Response.success(jsonObject2); + Mockito.when(intentApiService.getInstanceBandwidth(any())).thenReturn(mockCall2); + Mockito.when(mockCall2.execute()).thenReturn(response2); + + 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.getIntentInstanceBandwidth(); + } + + @Test + public void deleteIntentInstance() throws IOException { + IntentInstance instance = new IntentInstance(); + 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); + Mockito.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(); + + intentInstanceService.deleteIntentInstance("1"); + } + + @Test + public void activeIntentInstance() throws IOException { + IntentInstance instance = new IntentInstance(); + instance.setInstanceId("1"); + instance.setJobId("1"); + instance.setStatus("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); + JSONObject body = JSONObject.parseObject("{\"jobId\":\"123\"}"); + Response<JSONObject> response = Response.success(body); + Mockito.when(intentApiService.createIntentInstance(any())).thenReturn(mockCall); + Mockito.when(mockCall.execute()).thenReturn(response); + + 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.activeIntentInstance("1"); + + } + + @Test + 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\"}]}"); + Response<JSONObject> response = Response.success(body); + Mockito.when(intentApiService.queryNetworkRoute()).thenReturn(mockCall); + Mockito.when(mockCall.execute()).thenReturn(response); + Map<String, Object> result = (Map<String, Object>) intentInstanceService.queryAccessNodeInfo(); + assertEquals(((List)result.get("accessNodeList")).size(), 1); + } +}
\ 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 469efed2..a228b769 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 @@ -15,23 +15,35 @@ */ package org.onap.usecaseui.server.service.intent.impl; -import java.io.File; +import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import org.hibernate.query.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; +import org.mockito.Mock; import org.mockito.Mockito; import org.onap.usecaseui.server.bean.intent.IntentModel; import org.onap.usecaseui.server.util.ZipUtil; 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 static org.hamcrest.core.Is.is; 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; + @RunWith(PowerMockRunner.class) @PrepareForTest({ZipUtil.class}) @@ -42,14 +54,19 @@ class IntentServiceImplTest { @InjectMocks private IntentServiceImpl intentService; + @Mock + private SessionFactory sessionFactory; + + @Mock + private Session session; + @Before public void before() throws Exception { - //doReturn(session).when(sessionFactory,"openSession"); + MemberModifier.field(IntentServiceImpl.class, "sessionFactory").set(intentService , sessionFactory); + doReturn(session).when(sessionFactory,"openSession"); } - - //public String addModel(IntentModel model) - /*@Test + @Test public void addModelTest() throws Exception { IntentModel model = new IntentModel(); model.setId(1); @@ -57,29 +74,66 @@ class IntentServiceImplTest { doReturn(tx).when(session,"beginTransaction"); Serializable save = Mockito.mock(Serializable.class); Mockito.when(session.save(model)).thenReturn(save); + Mockito.doNothing().when(tx).commit(); + Mockito.doNothing().when(session).flush(); + assertEquals(intentService.addModel(model), "1"); - }*/ - /*@Test - public void activeModelFileTest() throws Exception { - IntentModel model = new IntentModel(); - String filePath = "filePath.zip"; - String parentPath = "parentPath"; - String unzipPath = "filePath"; - model.setFilePath(filePath); + } - File file=PowerMockito.mock(File.class); - PowerMockito.whenNew(File.class).withArguments(Mockito.anyString()).thenReturn(file); - PowerMockito.when(file.exists()).thenReturn(true); - PowerMockito.when(file.getParent()).thenReturn(model.getFilePath()); + @Test + public void listModelsTest() { + Query query = Mockito.mock(Query.class); + when(session.createQuery(anyString())).thenReturn(query); + List<IntentModel> list = new ArrayList<>(); + when(query.list()).thenReturn(list); + assertTrue(intentService.listModels().isEmpty()); + + } + + @Test + public void getModel() { + Query query = Mockito.mock(Query.class); + when(session.createQuery(anyString())).thenReturn(query); + when(query.setParameter("modelId", "1")).thenReturn(query); + when(query.uniqueResult()).thenReturn(null); + assertEquals(intentService.getModel("1"), null); + + } - assertThat(intentService.activeModelFile(model), is(unzipPath)); - }*/ @Test - public void activeModelFileModelIsNullTest() throws Exception { + public void deleteModel() throws Exception { + Transaction tx = Mockito.mock(Transaction.class); + doReturn(tx).when(session,"beginTransaction"); + Mockito.doNothing().when(session).delete(any()); + Mockito.doNothing().when(tx).commit(); + assertEquals(intentService.deleteModel("1"), "1"); + + } + @Test + public void activeModel() throws Exception { + Transaction tx = Mockito.mock(Transaction.class); + doReturn(tx).when(session,"beginTransaction"); + + Query query = Mockito.mock(Query.class); + when(session.createQuery(anyString())).thenReturn(query); + List<IntentModel> list = new ArrayList<>(); + IntentModel intentModel = new IntentModel(); + intentModel.setActive(1); + list.add(intentModel); + when(query.list()).thenReturn(list); + Serializable save = Mockito.mock(Serializable.class); + Mockito.when(session.save(any())).thenReturn(save); + + Mockito.doNothing().when(tx).commit(); + assertEquals(intentService.activeModel("1"), null); + + } + @Test + public void activeModelFileModelIsNullTest() { assertEquals(intentService.activeModelFile(null), null); } @Test - public void activeModelFileFilePathIsNullTest() throws Exception { + public void activeModelFileFilePathIsNullTest() { IntentModel model = new IntentModel(); assertEquals(intentService.activeModelFile(model), null); } 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 eb953e57..c1fb78f0 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 @@ -146,3 +146,57 @@ CREATE TABLE sort_master ( "language" varchar(50) NOT NULL, CONSTRAINT sort_master_pk PRIMARY KEY (sort_type, sort_code, language) ); + +-- ---------------------------- +-- Table structure for sort_master +-- ---------------------------- +DROP TABLE IF EXISTS instance_performance; +CREATE TABLE instance_performance +( + id integer not null, + job_id varchar(32), + resource_instance_id varchar(64), + bandwidth numeric, + date date, + max_bandwidth numeric, + CONSTRAINT instance_performance_pk PRIMARY KEY (id) +); + +-- ---------------------------- +-- Table structure for intent_instance +-- ---------------------------- +DROP TABLE IF EXISTS intent_instance; +CREATE TABLE intent_instance +( + id serial not null + constraint intent_instance_pk + primary key, + instance_id varchar(16), + job_id varchar(16), + progress integer, + status char, + resource_instance_id varchar(16), + name varchar(255), + cloud_point_name varchar(255), + access_point_one_name varchar(255), + access_point_one_band_width integer, + line_num varchar(64), + delete_state integer default 0 +); + +-- ---------------------------- +-- Table structure for intent_model +-- ---------------------------- +DROP TABLE IF EXISTS intent_model; +create table intent_model +( + id serial not null + constraint intent_model_pk + primary key, + model_name varchar(100) default NULL::character varying, + file_path varchar(500) default NULL::character varying, + create_time varchar(100) default NULL::character varying, + size numeric(10, 3), + active integer, + "modelType" integer default 0 +); |