feat:Add file transfer function
[usecase-ui/server.git] / server / src / main / java / org / onap / usecaseui / server / service / intent / impl / IntentServiceImpl.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.service.intent.impl;
17
18 import java.util.Arrays;
19 import java.util.Collections;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import javax.transaction.Transactional;
26
27 import org.hibernate.Query;
28 import org.hibernate.Session;
29 import org.hibernate.SessionFactory;
30 import org.hibernate.Transaction;
31 import org.onap.usecaseui.server.bean.HttpResponseResult;
32 import org.onap.usecaseui.server.bean.intent.IntentModel;
33 import org.onap.usecaseui.server.service.intent.IntentService;
34 import org.onap.usecaseui.server.util.HttpUtil;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.context.annotation.EnableAspectJAutoProxy;
39 import org.springframework.stereotype.Service;
40
41 @Service("IntentService")
42 @Transactional
43 @org.springframework.context.annotation.Configuration
44 @EnableAspectJAutoProxy
45 public class IntentServiceImpl implements IntentService {
46     private static final Logger logger = LoggerFactory.getLogger(IntentServiceImpl.class);
47
48     @Autowired
49     private SessionFactory sessionFactory;
50
51     private Session getSession() {
52         return sessionFactory.openSession();
53     }
54
55     private final static int MAX_NUMBER_OF_UES = 100000;
56     private final static int MIN_NUMBER_OF_UES = 1;
57     private final static int MAX_EXP_DATA_RATE_DL = 3000;
58     private final static int MIN_EXP_DATA_RATE_DL = 100;
59     private final static int MAX_EXP_DATA_RATE_UL = 3000;
60     private final static int MIN_EXP_DATA_RATE_UL = 100;
61     private final static int MAX_LATENCY = 200;
62     private final static int MIN_LATENCY = 10;
63
64
65     private final static List<String> GB_COMPANY = Arrays.asList(new String[] {"gbps", "gb"});
66     private final static List<String> MB_COMPANY = Arrays.asList(new String[] {"mbps", "mb"});
67
68     @Override
69     public String addModel(IntentModel model) {
70         try(Session session = getSession()){
71             if (null == model){
72                 logger.error("IntentServiceImpl addModel model is null!");
73                 return "0";
74             }
75             Transaction tx = session.beginTransaction();
76             session.save(model);
77             tx.commit();
78             session.flush();
79             return "1";
80         } catch (Exception e) {
81             logger.error("Details:" + e.getMessage());
82             return "0";
83         }
84
85
86     }
87
88     public List<IntentModel> listModels(){
89         try(Session session = getSession()){
90             StringBuffer hql =new StringBuffer("from IntentModel a where 1=1 ");
91             Query query = session.createQuery(hql.toString());
92             //query.setString("sortType",sortType);
93             List<IntentModel> list= query.list();
94             return list;
95         } catch (Exception e) {
96             logger.error("Details:" + e.getMessage());
97             return Collections.emptyList();
98         }
99     }
100
101     public IntentModel getModel(String modelId){
102         IntentModel result = null;
103
104         try(Session session = getSession()) {
105             result = (IntentModel)session.createQuery("from IntentModel where id = :modelId")
106                     .setParameter("modelId", Integer.parseInt(modelId)).uniqueResult();
107             logger.info("get model OK, id=" + modelId);
108
109         } catch (Exception e) {
110             logger.error("getodel occur exception:"+e);
111
112         }
113
114         return result;
115     }
116
117     public String deleteModel(String modelId){
118         Transaction tx = null;
119         String result="0";
120         if(modelId==null || modelId.trim().equals(""))
121             return  result;
122
123         try(Session session = getSession()) {
124             tx = session.beginTransaction();
125
126             IntentModel model = new IntentModel();
127             model.setId(Integer.parseInt(modelId));
128             session.delete(model);
129             tx.commit();
130             logger.info("delete model OK, id=" + modelId);
131
132             result="1";
133         } catch (Exception e) {
134             if(tx!=null){
135                 tx.rollback();
136             }
137             logger.error("deleteModel occur exception:"+e);
138
139         }
140         return result;
141     }
142
143     public IntentModel activeModel(String modelId){
144         Transaction tx = null;
145         IntentModel result=null;
146         if(modelId==null || modelId.trim().equals(""))
147             return result;
148
149         try(Session session = getSession()) {
150             tx = session.beginTransaction();
151             List<IntentModel> list = session.createQuery("from IntentModel where active=1").list();
152             if(list!=null && list.size()>0){
153                 for (IntentModel m : list) {
154                     m.setActive(0);
155                     session.save(m);
156                 }
157             }
158
159             IntentModel model = (IntentModel)session.createQuery("from IntentModel where id = :modelId")
160                     .setParameter("modelId", Integer.parseInt(modelId)).uniqueResult();
161             model.setActive(1);
162             session.save(model);
163             tx.commit();
164             logger.info("active model OK, id=" + modelId);
165
166             result = model;
167         } catch (Exception e) {
168             if(tx!=null){
169                 tx.rollback();
170             }
171             logger.error("deleteModel occur exception:"+e);
172
173         }
174         return result;
175     }
176
177     @Override
178     public String activeModelFile(IntentModel model) {
179         if (model == null) {
180             return null;
181         }
182         String fileName = model.getModelName();
183         if (fileName == null) {
184             return null;
185         }
186         else if (fileName.endsWith(".zip")){
187             try {
188                 postUnzipFile(fileName);
189                 return fileName;
190
191             }
192             catch (Exception e) {
193                 e.printStackTrace();
194             }
195         }
196         return fileName;
197     }
198
199     private String postUnzipFile(String fileName) {
200
201         String url = "http://uui-nlp:33013/unzipFile/"+ fileName;
202         HashMap<String, String> headers = new HashMap<>();
203
204         HttpResponseResult result = HttpUtil.sendGetRequest(url,headers);
205         String respContent = result.getResultContent();
206
207         logger.info("NLP api respond: " + String.valueOf(result.getResultCode()));
208         logger.info(respContent);
209
210         return respContent;
211     }
212
213     public String calcFieldValue(String key, String strValue){
214         String ret = "";
215
216
217         if(strValue==null)
218             strValue = "";
219         else
220             ret = strValue.trim();
221
222         if("resourceSharingLevel".equalsIgnoreCase(key)){
223             ret = formatValueForResourcesSharingLevel(strValue);
224         }
225         else if("uEMobilityLevel".equalsIgnoreCase(key)){
226             ret = formatValueForUEMobilitylevel(strValue);
227         }
228         else if("coverageArea".equalsIgnoreCase(key)){
229
230             ret = formatValueForCoverageArea(strValue);
231         }
232         else if ("maxNumberofUEs".equalsIgnoreCase(key)) {
233             ret = formatValueForMaxNumberofUEs(strValue);
234         }
235         else if ("expDataRateDL".equalsIgnoreCase(key)) {
236             ret = formatValueForExpDataRateDL(strValue);
237         }
238         else if ("expDataRateUL".equalsIgnoreCase(key)) {
239             ret = formatValueForExpDataRateUL(strValue);
240         }
241         else if ("latency".equalsIgnoreCase(key)) {
242             ret = formatValueForLatency(strValue);
243
244         }
245
246         return ret;
247     }
248
249     private String formatValueForLatency(String strValue) {
250         String ret;
251         if ("default".equalsIgnoreCase(strValue)) {
252             ret = MAX_LATENCY + "";
253         }
254         else if ("low".equalsIgnoreCase(strValue)) {
255             ret = MIN_LATENCY + "";
256         }
257         else {
258             Pattern pattern = Pattern.compile("(\\d+)([\\w ]*)");
259             Matcher matcher = pattern.matcher(strValue);
260
261
262             int dataRate = 10;
263             if (matcher.matches()) {
264                 dataRate = Integer.parseInt(matcher.group(1));
265                 String company = matcher.group(2).trim().toLowerCase();
266                 if ("s".equalsIgnoreCase(company)) {
267                     dataRate = dataRate * 1000;
268                 }
269                 else if (!"ms".equalsIgnoreCase(company)) {
270                     dataRate = MAX_LATENCY;
271                 }
272                 dataRate = dataRate < MIN_LATENCY ? MIN_LATENCY : (dataRate > MAX_LATENCY ? MAX_LATENCY : dataRate);
273             }
274             ret = dataRate + "";
275         }
276         return ret;
277     }
278
279     private String formatValueForExpDataRateUL(String strValue) {
280         String ret;
281         Pattern pattern = Pattern.compile("(\\d+)([\\w ]*)");
282         Matcher matcher = pattern.matcher(strValue);
283
284
285         int dataRate = 100;
286         if (matcher.matches()) {
287             dataRate = Integer.parseInt(matcher.group(1));
288             String company = matcher.group(2).trim().toLowerCase();
289             if (GB_COMPANY.contains(company)) {
290                 dataRate = dataRate * 1000;
291             }
292             else if (!MB_COMPANY.contains(company)) {
293                 dataRate = 100;
294             }
295             dataRate = dataRate < MIN_EXP_DATA_RATE_UL ? MIN_EXP_DATA_RATE_UL : (dataRate > MAX_EXP_DATA_RATE_UL ? MAX_EXP_DATA_RATE_UL : dataRate);
296         }
297         ret = dataRate + "";
298         return ret;
299     }
300
301     private String formatValueForExpDataRateDL(String strValue) {
302         String ret;
303         Pattern pattern = Pattern.compile("(\\d+)([\\w ]*)");
304         Matcher matcher = pattern.matcher(strValue);
305
306         int dataRate = 100;
307         if (matcher.matches()) {
308             dataRate = Integer.parseInt(matcher.group(1));
309             String company = matcher.group(2).trim().toLowerCase();
310             if (GB_COMPANY.contains(company)) {
311                 dataRate = dataRate * 1000;
312             }
313             else if (!MB_COMPANY.contains(company)) {
314                 dataRate = 100;
315             }
316             dataRate = dataRate < MIN_EXP_DATA_RATE_DL ? MIN_EXP_DATA_RATE_DL : (dataRate > MAX_EXP_DATA_RATE_DL ? MAX_EXP_DATA_RATE_DL : dataRate);
317         }
318
319         ret = dataRate + "";
320         return ret;
321     }
322
323     private String formatValueForMaxNumberofUEs(String strValue) {
324         String ret;
325         Pattern pattern = Pattern.compile("(\\d+)");
326         Matcher matcher = pattern.matcher(strValue);
327         int maxNumber = 1;
328         if (matcher.matches()) {
329             maxNumber = Integer.parseInt(matcher.group(1));
330             maxNumber = maxNumber < MIN_NUMBER_OF_UES ? MIN_NUMBER_OF_UES : (maxNumber > MAX_NUMBER_OF_UES ? MAX_NUMBER_OF_UES : maxNumber);
331         }
332         ret = maxNumber + "";
333         return ret;
334     }
335
336     private String formatValueForCoverageArea(String strValue) {
337         String ret;
338         Map<String, Object> areaMap = new HashMap<>();
339         areaMap.put("wanshoulu", "Beijing Haidian District Wanshoulu Street");
340         areaMap.put("zhongguancun", "Beijing Haidian District Zhongguancun");
341         areaMap.put("haidian", "Beijing Haidian District Haidian Street");
342         areaMap.put("xisanqi", "Beijing Haidian District Xisanqi Street");
343         areaMap.put("chengbei", "Beijing Changping District Chengbei Street");
344         areaMap.put("chengnan", "Beijing Changping District Chengnan Street");
345         areaMap.put("tiantongyuan north", "Beijing Changping District Tiantongyuan North Street");
346         areaMap.put("tiantongyuan south", "Beijing Changping District Tiantongyuan South Street");
347         areaMap.put("guang'anmenwai", "Beijing Xicheng District Guang'anmenwai Street");
348         areaMap.put("xuanwumen", "Beijing Xicheng District Xuanwumen Street");
349         areaMap.put("west changan", "Beijing Xicheng District West Changan Street");
350         areaMap.put("financial", "Beijing Xicheng District Financial Street");
351         areaMap.put("lujiazui", "Shanghai udongxin District Lujiazui Street");
352         areaMap.put("zhoujiadu", "Shanghai udongxin District Zhoujiadu Street");
353         areaMap.put("tangqiao", "Shanghai udongxin District Tangqiao Street");
354         areaMap.put("nanquanlu", "Shanghai udongxin District Nanquanlu Street");
355         areaMap.put("jiangning lu", "Shanghai Jingan District Jiangning Lu Street");
356         areaMap.put("jing'an temple", "Shanghai Jingan District Jing'an Temple Street");
357         areaMap.put("ningjing west road", "Shanghai Jingan District Ningjing West Road");
358
359         ret = "Beijing Beijing Haiding Wanshoulu";
360         for (Map.Entry<String, Object> entry : areaMap.entrySet()) {
361
362             if (strValue.toLowerCase().contains(entry.getKey())) {
363                 ret = entry.getValue().toString();
364             }
365         }
366         return ret;
367     }
368
369     private String formatValueForUEMobilitylevel(String strValue) {
370         String ret;
371         ret = "stationary";
372         if(strValue.contains("Nomadic")){
373             ret = "nomadic";
374         }
375         else if(strValue.contains("restricted")){
376             ret = "Spatially Restricted Mobility";
377         }
378         else if(strValue.contains("fully")){
379             ret = "Fully Mobility";
380         }
381         return ret;
382     }
383
384     private String formatValueForResourcesSharingLevel(String strValue) {
385         String ret;
386         ret = "no-shared";
387         if("shared".equalsIgnoreCase(strValue)){
388             ret = "shared";
389         }
390         return ret;
391     }
392
393
394     public String getActiveModelType() {
395         try(Session session = getSession()){
396             IntentModel model = (IntentModel) session.createQuery("from IntentModel where active = 1").uniqueResult();
397             return model.getModelType();
398         } catch (Exception e) {
399             logger.error("Details:" + e.getMessage());
400             return null;
401         }
402     }
403 }