feat:Add file transfer function
[usecase-ui/server.git] / server / src / main / java / org / onap / usecaseui / server / controller / IntentController.java
1 /*
2  * Copyright (C) 2021 CTC, Inc. and others. All rights reserved.
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 package org.onap.usecaseui.server.controller;
17
18 import java.io.File;
19 import java.io.IOException;
20 import java.text.ParseException;
21 import java.util.*;
22 import javax.annotation.Resource;
23
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;
40
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;
45
46 @RestController
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/";
55
56     @Resource(name = "IntentService")
57     private IntentService intentService;
58
59     @Resource(name = "IntentInstanceService")
60     private IntentInstanceService intentInstanceService;
61
62     private IntentApiService intentApiService;
63
64     private ObjectMapper omAlarm = new ObjectMapper();
65
66     @Resource(name = "SlicingService")
67     private SlicingService slicingService;
68
69     public IntentController() {
70         this(RestfulServices.create(IntentApiService.class));
71     }
72     public IntentController(IntentApiService intentApiService) {
73         this.intentApiService = intentApiService;
74     }
75
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);
80     }
81
82     @RequestMapping("/uploadModel")
83     @ResponseBody
84     public String uploadModel (@RequestParam("file") MultipartFile file,@RequestParam("modelType")String modelType) {
85         String fileName = file.getOriginalFilename();
86
87         String filePath = UPLOADPATH + fileName ;
88
89         File dest = new File(filePath);
90
91         if(!dest.getParentFile().exists()) {
92             dest.getParentFile().mkdirs();
93             logger.info("create dir, name=" + dest.getParentFile().getName());
94         }
95         try {
96
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);
106             model.setActive(0);
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);
111
112             intentService.addModel(model);
113
114             logger.info("save model, " + model.toString());
115             return "1";
116         } catch (Exception e) {
117             logger.error("Details:" + e.getMessage());
118             return "0";
119         }
120     }
121
122     private String deleteModelFile(String modelId){
123         String result = "0";
124         try{
125             IntentModel model = intentService.getModel(modelId);
126             if( model==null){
127                 return result;
128             }
129
130             String fileName = model.getModelName();
131             String filePath = UPLOADPATH + fileName;
132             logger.info("delete model file: " + filePath);
133             File dest = new File(filePath);
134             if(dest.exists()){
135                 dest.delete();
136                 postDeleteFile(fileName);
137                 logger.info("delete file OK: " + filePath);
138             }{
139                 logger.info("file not found: " + filePath);
140             }
141             result = "1";
142         }catch (Exception e){
143             logger.error("Details:" + e.getMessage());
144             return "0";
145         }
146         return result;
147     }
148
149
150     private String postDeleteFile(String fileName) {
151
152         String url = "http://uui-nlp:33013/deleteFile/"+ fileName;
153         HashMap<String, String> headers = new HashMap<>();
154
155         HttpResponseResult result = HttpUtil.sendGetRequest(url,headers);
156         String respContent = result.getResultContent();
157
158         logger.info("NLP api respond: " + String.valueOf(result.getResultCode()));
159         logger.info(respContent);
160
161         return respContent;
162     }
163
164     @GetMapping(value = {"/activeModel"}, produces = "application/json")
165     public String activeModel(@RequestParam String modelId){
166         String result = "0";
167         try{
168             logger.info("update model record status: id=" + modelId);
169             IntentModel model = intentService.activeModel(modelId);
170
171             logger.info("active NLP model, model=" + model.getFilePath());
172             String fileName = intentService.activeModelFile(model);
173             if (fileName != null) {
174                 load(NLPLOADPATH + fileName);
175             }
176
177
178             result = "1";
179         }catch (Exception e) {
180             logger.error("Details:" + e.getMessage());
181             return "0";
182         }
183
184         return result;
185     }
186
187     private String load(String dirPath) {
188
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);
193
194         HttpResponseResult result = HttpUtil.sendPostRequestByJson(url, headers, bodyStr);
195         String respContent = result.getResultContent();
196
197         logger.info("NLP api respond: " + String.valueOf(result.getResultCode()));
198         logger.info(respContent);
199
200         JSONObject map = JSON.parseObject(respContent);
201
202         String status = map.getString("Status");
203         logger.info("load result: " + status);
204
205         return status;
206     }
207
208     @DeleteMapping(value = {"/deleteModel"}, produces = "application/json")
209     public String deleteModel(@RequestParam String modelId){
210         String result = "0";
211         try{
212             result = deleteModelFile(modelId);
213
214             logger.info("delete model record: id=" + modelId);
215             result = intentService.deleteModel(modelId);
216         }catch (Exception e) {
217             logger.error("Details:" + e.getMessage());
218             return "0";
219         }
220
221         return result;
222     }
223
224     @ResponseBody
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");
230
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");
234         }
235
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
239                 +  "\"}";
240         logger.info("request body: " + bodyStr);
241
242         HttpResponseResult result = HttpUtil.sendPostRequestByJson(url, headers, bodyStr);
243         String respContent = result.getResultContent();
244
245         logger.info("NLP api respond: " + String.valueOf(result.getResultCode()));
246         logger.info(respContent);
247
248         JSONObject map = JSON.parseObject(respContent);
249
250         JSONObject map2 = new JSONObject();
251
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);
258         }
259
260         logger.info("translate result: " + map2.toJSONString());
261
262         return map2.toJSONString();
263     }
264
265
266
267     private static String tranlateFieldName(String key){
268         String ret = "";
269         if(key==null || key.trim().equals(""))
270             return ret;
271
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");
281
282         ret = map.get(key.trim());
283         return ret;
284     }
285
286     @IntentResponseBody
287     @ResponseBody
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;
295         }
296         String instanceId = first + String.format("%015d", hashCodeV);
297         JSONObject result = new JSONObject();
298         result.put("instanceId", instanceId);
299         return result;
300     }
301     @IntentResponseBody
302     @ResponseBody
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);
310     }
311     @IntentResponseBody
312     @ResponseBody
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");
323
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);
331
332         int flag = intentInstanceService.createIntentInstance(intentInstance);
333
334         if(flag == 1) {
335             return "OK";
336         }
337         else {
338             throw new RuntimeException("create Instance error");
339         }
340     }
341
342     @IntentResponseBody
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);
353         }
354         return result;
355     }
356
357     @IntentResponseBody
358     @ResponseBody
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);
364         return "ok";
365     }
366     @IntentResponseBody
367     @ResponseBody
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);
373         return "ok";
374     }
375     @IntentResponseBody
376     @ResponseBody
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);
382         return "ok";
383     }
384
385     @IntentResponseBody
386     @ResponseBody
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);
392     }
393
394     @IntentResponseBody
395     @GetMapping(value = {"/queryAccessNodeInfo"},
396             produces = "application/json")
397     public Object queryAccessNodeInfo() throws IOException{
398         return intentInstanceService.queryAccessNodeInfo();
399     }
400 }