2 * Copyright (C) 2021 CTC, Inc. and others. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.onap.usecaseui.server.controller;
19 import java.io.IOException;
20 import java.text.ParseException;
22 import javax.annotation.Resource;
24 import org.apache.commons.collections.MapUtils;
25 import org.onap.usecaseui.server.bean.HttpResponseResult;
26 import org.onap.usecaseui.server.bean.intent.IntentInstance;
27 import org.onap.usecaseui.server.bean.intent.IntentModel;
28 import org.onap.usecaseui.server.bean.intent.IntentResponseBody;
29 import org.onap.usecaseui.server.service.csmf.SlicingService;
30 import org.onap.usecaseui.server.service.intent.IntentApiService;
31 import org.onap.usecaseui.server.service.intent.IntentInstanceService;
32 import org.onap.usecaseui.server.service.intent.IntentService;
33 import org.onap.usecaseui.server.util.*;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.context.annotation.EnableAspectJAutoProxy;
37 import org.springframework.http.MediaType;
38 import org.springframework.web.bind.annotation.*;
39 import org.springframework.web.multipart.MultipartFile;
41 import com.alibaba.fastjson.JSON;
42 import com.alibaba.fastjson.JSONObject;
43 import com.fasterxml.jackson.core.JsonProcessingException;
44 import com.fasterxml.jackson.databind.ObjectMapper;
47 @org.springframework.context.annotation.Configuration
48 @EnableAspectJAutoProxy
49 @CrossOrigin(origins = "*")
50 @RequestMapping("/intent")
51 public class IntentController {
52 private final Logger logger = LoggerFactory.getLogger(IntentController.class);
53 private final static String UPLOADPATH = "/home/uui/upload/";
54 private final static String NLPLOADPATH = "/home/run/bert-master/upload/";
56 @Resource(name = "IntentService")
57 private IntentService intentService;
59 @Resource(name = "IntentInstanceService")
60 private IntentInstanceService intentInstanceService;
62 private IntentApiService intentApiService;
64 private ObjectMapper omAlarm = new ObjectMapper();
66 @Resource(name = "SlicingService")
67 private SlicingService slicingService;
69 public IntentController() {
70 this(RestfulServices.create(IntentApiService.class));
72 public IntentController(IntentApiService intentApiService) {
73 this.intentApiService = intentApiService;
76 @GetMapping(value="/listModel",produces = "application/json;charset=utf8")
77 public String getModels() throws JsonProcessingException {
78 List<IntentModel> listModels = intentService.listModels();
79 return omAlarm.writeValueAsString(listModels);
82 @RequestMapping("/uploadModel")
84 public String uploadModel (@RequestParam("file") MultipartFile file,@RequestParam("modelType")String modelType) {
85 String fileName = file.getOriginalFilename();
87 String filePath = UPLOADPATH + fileName ;
89 File dest = new File(filePath);
91 if(!dest.getParentFile().exists()) {
92 dest.getParentFile().mkdirs();
93 logger.info("create dir, name=" + dest.getParentFile().getName());
97 file.transferTo(dest);
98 logger.info("upload file, name = " + dest.getName());
99 IntentModel model = new IntentModel();
100 model.setModelName(fileName);
101 model.setFilePath(filePath);
102 model.setCreateTime(DateUtils.dateToString(new Date()));
103 float size = dest.length();
104 float sizeM = size/1024;
105 model.setSize(sizeM);
107 model.setModelType(modelType);
108 Map<String,String> fileMap = new HashMap<>();
109 fileMap.put("file", filePath);
110 UploadFileUtil.formUpload("http://uui-nlp:33013/uploader", null, fileMap, null);
112 intentService.addModel(model);
114 logger.info("save model, " + model.toString());
116 } catch (Exception e) {
117 logger.error("Details:" + e.getMessage());
122 private String deleteModelFile(String modelId){
125 IntentModel model = intentService.getModel(modelId);
130 String fileName = model.getModelName();
131 String filePath = UPLOADPATH + fileName;
132 logger.info("delete model file: " + filePath);
133 File dest = new File(filePath);
136 postDeleteFile(fileName);
137 logger.info("delete file OK: " + filePath);
139 logger.info("file not found: " + filePath);
142 }catch (Exception e){
143 logger.error("Details:" + e.getMessage());
150 private String postDeleteFile(String fileName) {
152 String url = "http://uui-nlp:33013/deleteFile/"+ fileName;
153 HashMap<String, String> headers = new HashMap<>();
155 HttpResponseResult result = HttpUtil.sendGetRequest(url,headers);
156 String respContent = result.getResultContent();
158 logger.info("NLP api respond: " + String.valueOf(result.getResultCode()));
159 logger.info(respContent);
164 @GetMapping(value = {"/activeModel"}, produces = "application/json")
165 public String activeModel(@RequestParam String modelId){
168 logger.info("update model record status: id=" + modelId);
169 IntentModel model = intentService.activeModel(modelId);
171 logger.info("active NLP model, model=" + model.getFilePath());
172 String fileName = intentService.activeModelFile(model);
173 if (fileName != null) {
174 load(NLPLOADPATH + fileName);
179 }catch (Exception e) {
180 logger.error("Details:" + e.getMessage());
187 private String load(String dirPath) {
189 String url = "http://uui-nlp.onap:33011/api/online/load";
190 HashMap<String, String> headers = new HashMap<>();
191 String bodyStr = "{" + "\"path\": \""+dirPath+"\"" + "}";
192 logger.info("request body: " + bodyStr);
194 HttpResponseResult result = HttpUtil.sendPostRequestByJson(url, headers, bodyStr);
195 String respContent = result.getResultContent();
197 logger.info("NLP api respond: " + String.valueOf(result.getResultCode()));
198 logger.info(respContent);
200 JSONObject map = JSON.parseObject(respContent);
202 String status = map.getString("Status");
203 logger.info("load result: " + status);
208 @DeleteMapping(value = {"/deleteModel"}, produces = "application/json")
209 public String deleteModel(@RequestParam String modelId){
212 result = deleteModelFile(modelId);
214 logger.info("delete model record: id=" + modelId);
215 result = intentService.deleteModel(modelId);
216 }catch (Exception e) {
217 logger.error("Details:" + e.getMessage());
225 @PostMapping(value = {"/predict"}, consumes = MediaType.APPLICATION_JSON_VALUE,
226 produces = "application/json; charset=utf-8")
227 public String predict(@RequestBody Object body) throws ParseException {
228 String text = (String)((Map)body).get("text");
229 String modelType = (String)((Map)body).get("modelType");
231 String activeModelType = intentService.getActiveModelType();
232 if (modelType == null || !modelType.equals(activeModelType)) {
233 throw new RuntimeException("The active model file does not support parsing the current text");
236 String url = "http://uui-nlp.onap:33011/api/online/predict";
237 HashMap<String, String> headers = new HashMap<>();
238 String bodyStr = "{\"title\": \"predict\", \"text\": \"" + text
240 logger.info("request body: " + bodyStr);
242 HttpResponseResult result = HttpUtil.sendPostRequestByJson(url, headers, bodyStr);
243 String respContent = result.getResultContent();
245 logger.info("NLP api respond: " + String.valueOf(result.getResultCode()));
246 logger.info(respContent);
248 JSONObject map = JSON.parseObject(respContent);
250 JSONObject map2 = new JSONObject();
252 for (Map.Entry<String, Object> entry:map.entrySet()) {
253 logger.debug(entry.getKey()+","+entry.getValue());
254 String key = tranlateFieldName(entry.getKey());
255 String valueStr = (String) entry.getValue();
256 String value = intentService.calcFieldValue(key, valueStr);
257 map2.put(key, value);
260 logger.info("translate result: " + map2.toJSONString());
262 return map2.toJSONString();
267 private static String tranlateFieldName(String key){
269 if(key==null || key.trim().equals(""))
272 HashMap<String, String> map = new HashMap<>();
273 map.put("Communication service","name");
274 map.put("Maximum user devices","maxNumberofUEs");
275 map.put("Downlink data rate","expDataRateDL");
276 map.put("Time delay","latency");
277 map.put("Uplink data rate","expDataRateUL");
278 map.put("Resource","resourceSharingLevel");
279 map.put("Mobility","uEMobilityLevel");
280 map.put("Region","coverageArea");
282 ret = map.get(key.trim());
288 @GetMapping(value = {"/getInstanceId"},
289 produces = "application/json")
290 public JSONObject getInstanceId() {
291 int first = new Random(10).nextInt(8) + 1;
292 int hashCodeV = UUID.randomUUID().toString().hashCode();
293 if (hashCodeV < 0) {//有可能是负数
294 hashCodeV = -hashCodeV;
296 String instanceId = first + String.format("%015d", hashCodeV);
297 JSONObject result = new JSONObject();
298 result.put("instanceId", instanceId);
303 @PostMapping (value = {"/getInstanceList"},consumes = MediaType.APPLICATION_JSON_VALUE,
304 produces = "application/json")
305 public Object getInstanceList(@RequestBody Object body) {
306 int currentPage = (int) ((Map)body).get("currentPage");
307 int pageSize = (int) ((Map)body).get("pageSize");
308 logger.error("getInstanceList --> currentPage:" + currentPage + ",pageSize:" + pageSize);
309 return intentInstanceService.queryIntentInstance(null, currentPage, pageSize);
313 @PostMapping(value = {"/createIntentInstance"}, consumes = MediaType.APPLICATION_JSON_VALUE,
314 produces = "application/json; charset=utf-8")
315 public Object createIntentInstance(@RequestBody Object body) throws IOException {
316 String intentInstanceId = (String) ((Map)body).get("instanceId");
317 String name = (String) ((Map)body).get("name");
318 String lineNum = (String) ((Map)body).get("lineNum");
319 String cloudPointName = (String) ((Map)body).get("cloudPointName");
320 Map<String, Object> accessPointOne = (Map) ((Map)body).get("accessPointOne");
321 String accessPointOneName = MapUtils.getString(accessPointOne, "name");
322 int accessPointOneBandWidth = MapUtils.getIntValue(accessPointOne, "bandwidth");
324 IntentInstance intentInstance = new IntentInstance();
325 intentInstance.setInstanceId(intentInstanceId);
326 intentInstance.setName(name);
327 intentInstance.setLineNum(lineNum);
328 intentInstance.setCloudPointName(cloudPointName);
329 intentInstance.setAccessPointOneName(accessPointOneName);
330 intentInstance.setAccessPointOneBandWidth(accessPointOneBandWidth);
332 int flag = intentInstanceService.createIntentInstance(intentInstance);
338 throw new RuntimeException("create Instance error");
343 @GetMapping(value = {"/getFinishedInstanceInfo"},
344 produces = "application/json")
345 public Object getFinishedInstanceInfo() {
346 List<IntentInstance> instanceList = intentInstanceService.getFinishedInstanceInfo();
347 List<Map<String, Object>> result = new ArrayList<>();
348 for (IntentInstance instance : instanceList) {
349 Map<String, Object> instanceInfo = new HashMap<>();
350 instanceInfo.put("instanceId", instance.getInstanceId());
351 instanceInfo.put("name", instance.getName());
352 result.add(instanceInfo);
359 @PostMapping(value = {"/deleteIntentInstance"}, consumes = MediaType.APPLICATION_JSON_VALUE,
360 produces = "application/json; charset=utf-8")
361 public Object deleteIntentInstance(@RequestBody Object body) {
362 String instanceId= (String) ((Map)body).get("instanceId");
363 intentInstanceService.deleteIntentInstance(instanceId);
368 @PostMapping(value = {"/activeIntentInstance"}, consumes = MediaType.APPLICATION_JSON_VALUE,
369 produces = "application/json; charset=utf-8")
370 public Object activeIntentInstance(@RequestBody Object body) {
371 String instanceId= (String) ((Map)body).get("instanceId");
372 intentInstanceService.activeIntentInstance(instanceId);
377 @PostMapping(value = {"/invalidIntentInstance"}, consumes = MediaType.APPLICATION_JSON_VALUE,
378 produces = "application/json; charset=utf-8")
379 public Object invalidIntentInstance(@RequestBody Object body) {
380 String instanceId= (String) ((Map)body).get("instanceId");
381 intentInstanceService.invalidIntentInstance(instanceId);
387 @PostMapping(value = {"/queryInstancePerformanceData"}, consumes = MediaType.APPLICATION_JSON_VALUE,
388 produces = "application/json; charset=utf-8")
389 public Object queryInstancePerformanceData(@RequestBody Object body) {
390 String instanceId= (String) ((Map)body).get("instanceId");
391 return intentInstanceService.queryInstancePerformanceData(instanceId);
395 @GetMapping(value = {"/queryAccessNodeInfo"},
396 produces = "application/json")
397 public Object queryAccessNodeInfo() throws IOException{
398 return intentInstanceService.queryAccessNodeInfo();