feat:Adjust ccvpn performance monitoring time and display unit.
[usecase-ui/server.git] / server / src / main / java / org / onap / usecaseui / server / service / intent / impl / IntentInstanceServiceImpl.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 com.alibaba.fastjson.JSON;
19 import com.alibaba.fastjson.JSONArray;
20 import com.alibaba.fastjson.JSONObject;
21 import org.hibernate.Query;
22 import org.hibernate.Session;
23 import org.hibernate.SessionFactory;
24 import org.hibernate.Transaction;
25 import org.onap.usecaseui.server.bean.csmf.ServiceCreateResult;
26 import org.onap.usecaseui.server.bean.csmf.SlicingOrder;
27 import org.onap.usecaseui.server.bean.intent.InstancePerformance;
28 import org.onap.usecaseui.server.bean.intent.CCVPNInstance;
29 import org.onap.usecaseui.server.bean.intent.IntentInstance;
30 import org.onap.usecaseui.server.bean.nsmf.common.ServiceResult;
31 import org.onap.usecaseui.server.constant.IntentConstant;
32 import org.onap.usecaseui.server.service.csmf.SlicingService;
33 import org.onap.usecaseui.server.service.intent.IntentApiService;
34 import org.onap.usecaseui.server.service.intent.IntentInstanceService;
35 import org.onap.usecaseui.server.service.lcm.domain.so.SOService;
36 import org.onap.usecaseui.server.service.nsmf.ResourceMgtService;
37 import org.onap.usecaseui.server.util.Page;
38 import org.onap.usecaseui.server.util.RestfulServices;
39 import org.onap.usecaseui.server.util.UuiCommonUtil;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.context.annotation.EnableAspectJAutoProxy;
44 import org.springframework.stereotype.Service;
45 import retrofit2.Call;
46 import retrofit2.Response;
47
48 import javax.annotation.Resource;
49 import javax.transaction.Transactional;
50 import java.io.*;
51 import java.text.SimpleDateFormat;
52 import java.util.*;
53 import java.util.regex.Matcher;
54 import java.util.regex.Pattern;
55
56 @Service("IntentInstanceService")
57 @Transactional
58 @org.springframework.context.annotation.Configuration
59 @EnableAspectJAutoProxy
60 public class IntentInstanceServiceImpl implements IntentInstanceService {
61     private static final Logger logger = LoggerFactory.getLogger(IntentInstanceServiceImpl.class);
62
63     @Autowired
64     private SessionFactory sessionFactory;
65
66     @Resource(name = "ResourceMgtService")
67     private ResourceMgtService resourceMgtService;
68
69     @Resource(name = "SlicingService")
70     private SlicingService slicingService;
71
72     private IntentApiService intentApiService;
73
74     private SOService soService;
75
76     private final static int MAX_BANDWIDTH = 6000;
77     private final static int MIN_BANDWIDTH = 100;
78
79     private final static List<String> GB_COMPANY = Arrays.asList(new String[] {"gbps", "gb"});
80     private final static List<String> MB_COMPANY = Arrays.asList(new String[] {"mbps", "mb"});
81
82     public IntentInstanceServiceImpl() {
83         this(RestfulServices.create(IntentApiService.class),RestfulServices.create(SOService.class));
84     }
85     public IntentInstanceServiceImpl(IntentApiService intentApiService, SOService soService) {
86         this.intentApiService = intentApiService;
87         this.soService = soService;
88     }
89
90     private Session getSession() {
91         return sessionFactory.openSession();
92     }
93
94     @Override
95     public Page<CCVPNInstance> queryIntentInstance(CCVPNInstance instance, int currentPage, int pageSize) {
96         Page<CCVPNInstance> page = new Page<CCVPNInstance>();
97         int allRow =this.getAllCount(instance,currentPage,pageSize);
98         int offset = page.countOffset(currentPage, pageSize);
99         Session session = getSession();
100         try{
101             StringBuffer hql =new StringBuffer("from CCVPNInstance a where deleteState = 0");
102             if (null != instance) {
103                 if(UuiCommonUtil.isNotNullOrEmpty(instance.getInstanceId())) {
104                     String ver =instance.getInstanceId();
105                     hql.append(" and a.instance_id = '"+ver+"'");
106                 }
107                 if(UuiCommonUtil.isNotNullOrEmpty(instance.getJobId())) {
108                     String ver =instance.getJobId();
109                     hql.append(" and a.job_id = '"+ver+"'");
110                 }
111                 if(UuiCommonUtil.isNotNullOrEmpty(instance.getStatus())) {
112                     String ver =instance.getStatus();
113                     hql.append(" and a.status = '"+ver+"'");
114                 }
115             }
116             hql.append(" order by id");
117             logger.info("AlarmsHeaderServiceImpl queryIntentInstance: instance={}", instance);
118             Query query = session.createQuery(hql.toString());
119             query.setFirstResult(offset);
120             query.setMaxResults(pageSize);
121             List<CCVPNInstance> list= query.list();
122             page.setPageNo(currentPage);
123             page.setPageSize(pageSize);
124             page.setTotalRecords(allRow);
125             page.setList(list);
126             return page;
127         } catch (Exception e) {
128             logger.error("exception occurred while performing AlarmsHeaderServiceImpl queryAlarmsHeader. Details:" + e.getMessage());
129             return null;
130         } finally {
131             session.close();
132         }
133     }
134
135
136     public int getAllCount(CCVPNInstance instance, int currentPage, int pageSize) {
137         Session session = getSession();
138         try{
139             StringBuffer count=new StringBuffer("select count(*) from CCVPNInstance a where deleteState = 0");
140             if (null != instance) {
141                 if(UuiCommonUtil.isNotNullOrEmpty(instance.getInstanceId())) {
142                     String ver =instance.getInstanceId();
143                     count.append(" and a.instance_id = '"+ver+"'");
144                 }
145                 if(UuiCommonUtil.isNotNullOrEmpty(instance.getJobId())) {
146                     String ver =instance.getJobId();
147                     count.append(" and a.job_id = '"+ver+"'");
148                 }
149                 if(UuiCommonUtil.isNotNullOrEmpty(instance.getStatus())) {
150                     String ver =instance.getStatus();
151                     count.append(" and a.status = '"+ver+"'");
152                 }
153             }
154             Query query = session.createQuery(count.toString());
155             long q=(long)query.uniqueResult();
156             return (int)q;
157         } catch (Exception e) {
158             logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
159             return -1;
160         } finally {
161             session.close();
162         }
163     }
164
165     @Override
166     public int createCCVPNInstance(CCVPNInstance instance) {
167         Session session = getSession();
168         Transaction tx = null;
169         try{
170
171             if (null == instance){
172                 logger.error("instance is null!");
173                 return 0;
174             }
175             String jobId = createIntentInstanceToSO(instance);
176             if (null == jobId){
177                 logger.error("create Instance error:jobId is null");
178                 return 0;
179             }
180             instance.setJobId(jobId);
181             instance.setResourceInstanceId("cll-"+instance.getInstanceId());
182             saveIntentInstanceToAAI(null, instance);
183
184             tx = session.beginTransaction();
185             session.save(instance);
186             tx.commit();
187             return 1;
188         } catch (Exception e) {
189             if (tx != null) {
190                 tx.rollback();
191             }
192             logger.error("Details:" + e.getMessage());
193             return 0;
194         } finally {
195             session.close();
196         }
197     }
198
199     public String createIntentInstanceToSO(CCVPNInstance instance) throws IOException {
200         Map<String, Object> params = new HashMap<>();
201         params.put("name", instance.getName());
202         params.put("modelInvariantUuid", "6790ab0e-034f-11eb-adc1-0242ac120002");
203         params.put("modelUuid", "6790ab0e-034f-11eb-adc1-0242ac120002");
204         params.put("globalSubscriberId", "IBNCustomer");
205         params.put("subscriptionServiceType", "IBN");
206         params.put("serviceType", "CLL");
207         Map<String, Object> additionalProperties = new HashMap<>();
208         additionalProperties.put("enableSdnc", "true");
209         additionalProperties.put("serviceInstanceID", "cll-" + instance.getInstanceId());
210         List<Map<String, Object>> transportNetworks = new ArrayList<>();
211         Map<String, Object> transportNetwork = new HashMap<>();
212         transportNetwork.put("id", "");
213         Map<String, Object> sla = new HashMap<>();
214         sla.put("latency", "2");
215         sla.put("maxBandwidth", instance.getAccessPointOneBandWidth());
216         List<Map<String, Object>> connectionLinks = new ArrayList<>();
217         Map<String, Object> connectionLink = new HashMap<>();
218         connectionLink.put("name", "");
219         connectionLink.put("transportEndpointA", instance.getAccessPointOneName());
220         connectionLink.put("transportEndpointB", instance.getCloudPointName());
221         connectionLinks.add(connectionLink);
222         if (instance.getProtectStatus() == 1) {
223             sla.put("protectionType", instance.getProtectionType());
224             connectionLink.put("transportEndpointBProtection", instance.getProtectionCloudPointName());
225         }
226         transportNetwork.put("sla", sla);
227         transportNetwork.put("connectionLinks", connectionLinks);
228         transportNetworks.add(transportNetwork);
229         additionalProperties.put("transportNetworks", transportNetworks);
230         params.put("additionalProperties",additionalProperties);
231
232         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
233         Response<JSONObject> response = intentApiService.createIntentInstance(requestBody).execute();
234         if (response.isSuccessful()) {
235             return response.body().getString("jobId");
236         }
237         return null;
238     }
239
240     @Override
241     public void getIntentInstanceProgress() {
242         List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("0");
243         for (CCVPNInstance instance: instanceList) {
244             try {
245
246                 int progress = getProgressByJobId(instance);
247                 instance.setProgress(progress);
248                 if (progress >=100) {
249                     instance.setStatus("1");
250                     saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId(),instance);
251                 }
252             }
253             catch (Exception e) {
254                 logger.info("get progress exception:"+e);
255             }
256         }
257         saveProgress(instanceList);
258
259     }
260     @Override
261     public void getIntentInstanceCreateStatus() {
262         List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("0");
263         for (CCVPNInstance instance: instanceList) {
264             try {
265
266                 int flag = getCreateStatusByJobId(instance);
267                 if (flag > 0) {
268                     instance.setStatus(flag + "");
269                     saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId(),instance);
270                 }
271             }
272             catch (Exception e) {
273                 logger.info("get progress exception:"+e);
274             }
275         }
276         saveProgress(instanceList);
277
278     }
279
280     private void saveProgress(List<CCVPNInstance> instanceList) {
281         if(instanceList == null || instanceList.isEmpty()) {
282             return;
283         }
284         Session session = getSession();
285         Transaction tx = null;
286         try {
287             tx = session.beginTransaction();
288             for (CCVPNInstance instance : instanceList) {
289                 session.update(instance);
290                 session.flush();
291             }
292             tx.commit();
293             logger.info("update progress ok");
294
295         } catch (Exception e) {
296             if(tx!=null){
297                 tx.rollback();
298             }
299             logger.error("update progress exception:"+e);
300
301         } finally {
302             session.close();
303         }
304     }
305
306     private int getProgressByJobId(CCVPNInstance instance) throws IOException {
307         Response<JSONObject> response = intentApiService.queryOperationProgress(instance.getResourceInstanceId(), instance.getJobId()).execute();
308         logger.debug(response.toString());
309         if (response.isSuccessful()) {
310             if (response.body().containsKey("operation")) {
311                 return response.body().getJSONObject("operation").getInteger("progress");
312             }
313         }
314         return -1;
315     }
316
317     private int getCreateStatusByJobId(CCVPNInstance instance) throws IOException {
318         if (instance == null || instance.getResourceInstanceId() == null) {
319             return -1;
320         }
321         Response<JSONObject> response = intentApiService.getInstanceInfo(instance.getResourceInstanceId()).execute();
322         logger.debug(response.toString());
323         if (response.isSuccessful()) {
324             String status = response.body().getString("orchestration-status");
325             if ("created".equals(status)) {
326                 return 1;
327             }
328             return 0;
329         }
330         logger.error("getIntentInstance Create Statue Error:" + response.toString());
331         return -1;
332     }
333
334     private List<CCVPNInstance> getInstanceByFinishedFlag(String flag) {
335         Session session = getSession();
336         try{
337             StringBuffer sql=new StringBuffer("from CCVPNInstance where deleteState = 0 and status = '" + flag + "'");
338
339             Query query = session.createQuery(sql.toString());
340             List<CCVPNInstance> q=(List<CCVPNInstance>) query.list();
341             logger.debug(q.toString());
342             return q;
343         } catch (Exception e) {
344             logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
345             return null;
346         } finally {
347             session.close();
348         }
349     }
350
351
352     @Override
353     public List<CCVPNInstance> getFinishedInstanceInfo() {
354         Session session = getSession();
355         try{
356             StringBuffer count=new StringBuffer("from CCVPNInstance where status = '1' and deleteState = 0");
357
358             Query query = session.createQuery(count.toString());
359             List<CCVPNInstance> q=(List<CCVPNInstance>) query.list();
360             logger.debug(q.toString());
361             return q;
362         } catch (Exception e) {
363             logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
364             return null;
365         } finally {
366             session.close();
367         }
368     }
369
370     @Override
371     public void getIntentInstanceBandwidth() throws IOException {
372         List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("1");
373         for (CCVPNInstance instance : instanceList) {
374             String serviceInstanceId = instance.getResourceInstanceId();
375             Response<JSONObject> response = intentApiService.getInstanceNetworkInfo(serviceInstanceId).execute();
376             if (!response.isSuccessful()) {
377                 logger.error("get Intent-Instance Bandwidth error:" + response.toString());
378                 continue;
379             }
380             JSONObject responseBody = response.body();
381             JSONObject allottedResource = responseBody.getJSONObject("allotted-resources").getJSONArray("allotted-resource").getJSONObject(0);
382             JSONArray relationshipList = allottedResource.getJSONObject("relationship-list").getJSONArray("relationship");
383             String networkPolicyId = null;
384             for (int i = 0; i<relationshipList.size();i++) {
385                 if ("network-policy".equals(relationshipList.getJSONObject(i).getString("related-to"))) {
386                     JSONArray datas = relationshipList.getJSONObject(i).getJSONArray("relationship-data");
387                     for (int j = 0; j<relationshipList.size();j++) {
388                         if ("network-policy.network-policy-id".equals(datas.getJSONObject(j).getString("relationship-key"))) {
389                             networkPolicyId = datas.getJSONObject(j).getString("relationship-value");
390                             break;
391                         }
392                     }
393                     break;
394                 }
395             }
396             if (networkPolicyId== null) {
397                 logger.error("get network Policy Id exception. serviceInstanceId:" + instance.getResourceInstanceId());
398                 continue;
399             }
400
401             Response<JSONObject> networkPolicyInfoResponse = intentApiService.getInstanceNetworkPolicyInfo(networkPolicyId).execute();
402             if (!networkPolicyInfoResponse.isSuccessful()) {
403                 logger.error("get Intent-Instance networkPolicyInfo error:" + networkPolicyInfoResponse.toString());
404                 continue;
405             }
406             JSONObject networkPolicyInfo = networkPolicyInfoResponse.body();
407             int maxBandwidth =  networkPolicyInfo.getIntValue("max-bandwidth") * 1000;
408             InstancePerformance instancePerformance = new InstancePerformance();
409             instancePerformance.setMaxBandwidth(maxBandwidth);
410             instancePerformance.setResourceInstanceId(instance.getResourceInstanceId());
411             instancePerformance.setJobId(instance.getJobId());
412             instancePerformance.setDate(new Date());
413
414             Response<JSONObject> metadatumResponse = intentApiService.getInstanceBandwidth(serviceInstanceId).execute();
415             if (!metadatumResponse.isSuccessful()) {
416                 logger.error("get Intent-Instance metadatum error:" + metadatumResponse.toString());
417                 continue;
418             }
419             JSONObject metadatum = metadatumResponse.body();
420             int metaval = metadatum.getJSONArray("metadatum").getJSONObject(0).getIntValue("metaval");
421             instancePerformance.setBandwidth(metaval);
422
423             Session session = getSession();
424             Transaction tx = null;
425             try{
426                 tx = session.beginTransaction();
427                 session.save(instancePerformance);
428                 tx.commit();
429             } catch (Exception e) {
430                 if(tx!=null){
431                     tx.rollback();
432                 }
433                 logger.error("Details:" + e.getMessage());
434             } finally {
435                 session.close();
436             }
437
438
439         }
440     }
441
442     @Override
443     public void deleteIntentInstance(String instanceId) {
444         CCVPNInstance result = null;
445         Session session = getSession();
446         try {
447
448             result = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
449                     .setParameter("instanceId", instanceId).uniqueResult();
450             logger.info("get CCVPNInstance OK, id=" + instanceId);
451
452         } catch (Exception e) {
453             logger.error("getodel occur exception:"+e);
454
455         } finally {
456             session.close();
457         }
458         try {
459             String serviceInstanceId = result.getResourceInstanceId();
460             deleteInstanceToSO(serviceInstanceId);
461             deleteIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-"+instanceId);
462             deleteInstance(result);
463         }catch (Exception e) {
464             logger.error("delete instance to SO error :" + e);
465         }
466     }
467
468
469     private void deleteInstanceToSO(String serviceInstanceId) throws IOException {
470         JSONObject params = new JSONObject();
471         params.put("serviceInstanceID", serviceInstanceId);
472         params.put("globalSubscriberId", "IBNCustomer");
473         params.put("subscriptionServiceType", "IBN");
474         params.put("serviceType", "CLL");
475         JSONObject additionalProperties = new JSONObject();
476         additionalProperties.put("enableSdnc", "false");
477         params.put("additionalProperties", additionalProperties);
478         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
479         intentApiService.deleteIntentInstance(requestBody).execute();
480     }
481     private String deleteInstance(CCVPNInstance instance) {
482         Transaction tx = null;
483         String result="0";
484         Session session = getSession();
485         try {
486             tx = session.beginTransaction();
487
488             session.delete(instance);
489             tx.commit();
490             logger.info("delete instance OK, id=" + instance.getInstanceId());
491
492             result="1";
493         } catch (Exception e) {
494             if(tx!=null){
495                 tx.rollback();
496             }
497             logger.error("delete instance occur exception:"+e);
498
499         } finally {
500             session.close();
501         }
502         return result;
503     }
504
505     @Override
506     public void activeIntentInstance(String instanceId) {
507         CCVPNInstance instance = null;
508         Session session = getSession();
509         Transaction tx = null;
510         try {
511
512             instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId and status = :status")
513                     .setParameter("instanceId", instanceId).setParameter("status", "3").uniqueResult();
514             logger.info("get instance OK, id=" + instanceId);
515
516             if (null == instance) {
517                 logger.error("instance is null!");
518                 return;
519             }
520
521             String jobId = createIntentInstanceToSO(instance);
522             instance.setStatus("0");
523             instance.setJobId(jobId);
524             tx = session.beginTransaction();
525             session.save(instance);
526             tx.commit();
527
528         }catch (Exception e) {
529             if(tx!=null){
530                 tx.rollback();
531             }
532             logger.error("active instance to SO error :" + e);
533         } finally {
534             session.close();
535         }
536     }
537
538     public void invalidIntentInstance(String instanceId) {
539         CCVPNInstance instance = null;
540         Session session = getSession();
541         Transaction tx = null;
542         try {
543             instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
544                     .setParameter("instanceId", instanceId).uniqueResult();
545             logger.info("get instance OK, id=" + instanceId);
546
547             if (null == instance) {
548                 logger.error("instance is null!");
549                 return;
550             }
551             deleteInstanceToSO(instance.getInstanceId());
552             instance.setStatus("3");
553             tx = session.beginTransaction();
554             session.save(instance);
555             session.flush();
556             tx.commit();
557
558         }catch (Exception e) {
559             if(tx!=null){
560                 tx.rollback();
561             }
562             logger.error("invalid instance to SO error :" + e);
563         } finally {
564             session.close();
565         }
566     }
567
568     @Override
569     public Map<String, Object> queryInstancePerformanceData(String instanceId) {
570         Session session = getSession();
571         try {
572             String hql = "from CCVPNInstance i, InstancePerformance p where i.resourceInstanceId = p.resourceInstanceId and  i.instanceId = :instanceId and i.deleteState = 0 order by p.date";
573             Query query = session.createQuery(hql).setParameter("instanceId", instanceId);
574             List<Object[]> queryResult= query.list();
575             List<String> date = new ArrayList<>();
576             List<Integer> bandwidth = new ArrayList<>();
577             List<Integer> maxBandwidth = new ArrayList<>();
578             SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
579             for (int i = queryResult.size() > 50? queryResult.size() - 50 : 0; i < queryResult.size(); i++) {
580                 Object[] o = queryResult.get(i);
581                 InstancePerformance performance = (InstancePerformance) o[1];
582                 date.add(ft.format(performance.getDate()));
583                 bandwidth.add(performance.getBandwidth());
584                 maxBandwidth.add(performance.getMaxBandwidth());
585             }
586             Map<String, Object> xAxis = new HashMap<>();
587             xAxis.put("data",date);
588             Map<String, Object> bandwidthData = new HashMap<>();
589             bandwidthData.put("data",bandwidth);
590             Map<String, Object> maxBandwidthData = new HashMap<>();
591             maxBandwidthData.put("data",maxBandwidth);
592             List<Map<String, Object>> series = new ArrayList<>();
593             series.add(bandwidthData);
594             series.add(maxBandwidthData);
595
596             Map<String, Object> result = new HashMap<>();
597             result.put("xAxis", xAxis);
598             result.put("series", series);
599
600             return result;
601         }catch (Exception e) {
602             logger.error("invalid instance to SO error :" + e);
603             throw e;
604         } finally {
605             session.close();
606         }
607     }
608
609     @Override
610     public Object queryAccessNodeInfo() throws IOException {
611         Map<String, Object> result = new HashMap<>();
612         List<String> accessNodeList = new ArrayList<>();
613         List<String> cloudAccessNodeList = new ArrayList<>();
614         Response<JSONObject> response = intentApiService.queryNetworkRoute().execute();
615         if (!response.isSuccessful()) {
616             logger.error(response.toString());
617             throw new RuntimeException("Query Access Node Info Error");
618         }
619         JSONObject body = response.body();
620         JSONArray data = body.getJSONArray("network-route");
621         for (int i = 0; i<data.size(); i++) {
622             JSONObject nodeInfo = data.getJSONObject(i);
623             if ("ROOT".equals(nodeInfo.getString("type"))) {
624                 cloudAccessNodeList.add(nodeInfo.getString("route-id"));
625             }
626             else {
627                 accessNodeList.add(nodeInfo.getString("route-id"));
628             }
629         }
630         result.put("accessNodeList",accessNodeList);
631         result.put("cloudAccessNodeList",cloudAccessNodeList);
632         return result;
633     }
634
635     @Override
636     public JSONObject getInstanceStatus(JSONArray ids) {
637         Session session = getSession();
638         try {
639             JSONObject result = new JSONObject();
640             JSONArray instanceInfos = new JSONArray();
641             String hql = "from CCVPNInstance i where i.instanceId in (:ids)";
642             Query query = session.createQuery(hql).setParameter("ids", ids);
643             List<CCVPNInstance> queryResult= query.list();
644             if (queryResult != null && queryResult.size() > 0) {
645                 for (CCVPNInstance instance : queryResult) {
646                     JSONObject instanceInfo = new JSONObject();
647                     instanceInfo.put("id", instance.getInstanceId());
648                     instanceInfo.put("status", instance.getStatus());
649                     instanceInfos.add(instanceInfo);
650                 }
651             }
652             result.put("IntentInstances",instanceInfos);
653             return result;
654
655         } catch (Exception e) {
656             logger.error("get Instance status error : " + e.getMessage());
657             throw e;
658         } finally {
659             session.close();
660         }
661     }
662
663
664     public String formatBandwidth(String strValue) {
665         String ret;
666         Pattern pattern = Pattern.compile("(\\d+)([\\w ]*)");
667         Matcher matcher = pattern.matcher(strValue);
668
669
670         int dataRate = 100;
671         if (matcher.matches()) {
672             dataRate = Integer.parseInt(matcher.group(1));
673             String company = matcher.group(2).trim().toLowerCase();
674             if (GB_COMPANY.contains(company)) {
675                 dataRate = dataRate * 1000;
676             }
677             else if (!MB_COMPANY.contains(company)) {
678                 dataRate = 100;
679             }
680             dataRate = dataRate < MIN_BANDWIDTH ? MIN_BANDWIDTH : (dataRate > MAX_BANDWIDTH ? MAX_BANDWIDTH : dataRate);
681         }
682         ret = dataRate + "";
683         return ret;
684     }
685
686
687     public String formatCloudPoint(String cloudPoint) {
688         String cloudPointAlias = "";
689         switch (cloudPoint) {
690             case "Cloud one" :
691                 cloudPointAlias = "tranportEp_dst_ID_212_1";
692                 break;
693         }
694         return cloudPointAlias;
695     }
696
697     public String formatAccessPoint(String accessPoint) {
698         String accessPointAlias = "";
699         switch (accessPoint) {
700             case "Access one" :
701                 accessPointAlias = "tranportEp_src_ID_111_1";
702                 break;
703             case "Access two" :
704                 accessPointAlias = "tranportEp_src_ID_111_2";
705                 break;
706             case "Access three" :
707                 accessPointAlias = "tranportEp_src_ID_113_1";
708                 break;
709         }
710         return accessPointAlias;
711     }
712
713     public void addCustomer() throws IOException {
714         Properties environment = getProperties();
715         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
716         Response<JSONObject> queryCustomerResponse = intentApiService.queryCustomer(globalCustomerId).execute();
717         if (queryCustomerResponse.isSuccessful()) {
718             return;
719         }
720         String subscriberName = environment.getProperty("ccvpn.subscriberName");
721         String subscriberType = environment.getProperty("ccvpn.subscriberType");
722         Map<String, Object> params = new HashMap<>();
723         params.put("global-customer-id", globalCustomerId);
724         params.put("subscriber-name", subscriberName);
725         params.put("subscriber-type", subscriberType);
726         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
727         intentApiService.addCustomer(globalCustomerId, requestBody).execute();
728     }
729
730     @Override
731     public IntentInstance createIntentInstance(Object body,String businessInstanceId, String businessInstance, String type) {
732         IntentInstance instance = new IntentInstance();
733         if (IntentConstant.MODEL_TYPE_CCVPN.equals(type)) {
734             assembleIntentInstanceFormCCVPNInfo(instance, body);
735         }
736         else if (IntentConstant.MODEL_TYPE_5GS.equals(type)) {
737             assembleIntentInstanceFormSliceInfo(instance, body);
738         }
739         instance.setIntentSource(type);
740         instance.setBusinessInstanceId(businessInstanceId);
741         instance.setBusinessInstance(businessInstance);
742         Session session = getSession();
743         Transaction tx = null;
744         try{
745             tx = session.beginTransaction();
746             session.save(instance);
747             tx.commit();
748             return instance;
749         } catch (Exception e) {
750             if (tx != null) {
751                 tx.rollback();
752             }
753             logger.error("createIntentInstance Details:" + e.getMessage());
754             return null;
755         } finally {
756             session.close();
757         }
758     }
759
760     private IntentInstance assembleIntentInstanceFormCCVPNInfo(IntentInstance instance, Object body) {
761         JSONObject jsonObject = new JSONObject((Map) body);
762         String intent_content = jsonObject.getString("intentContent");
763         jsonObject.remove("intentContent");
764         instance.setIntentConfig(jsonObject.toJSONString());
765         instance.setIntentContent(intent_content);
766         instance.setIntentName(jsonObject.getString("name"));
767         return instance;
768     }
769
770     private IntentInstance assembleIntentInstanceFormSliceInfo(IntentInstance instance, Object body) {
771         JSONObject jsonObject = new JSONObject((Map) body);
772         JSONObject slicingOrderInfo = jsonObject.getJSONObject("slicing_order_info");
773         String intent_content = slicingOrderInfo.getString("intentContent");
774         slicingOrderInfo.remove("intentContent");
775         instance.setIntentConfig(slicingOrderInfo.toJSONString());
776         instance.setIntentContent(intent_content);
777         instance.setIntentName(slicingOrderInfo.getString("name"));
778         return instance;
779     }
780
781
782     @Override
783     public void deleteIntent(int id) {
784         Transaction tx = null;
785         Session session = getSession();
786         try {
787             IntentInstance intentInstance = (IntentInstance)session.createQuery("from IntentInstance where id = :id")
788                     .setParameter("id", id).uniqueResult();
789             if (IntentConstant.MODEL_TYPE_CCVPN.equals(intentInstance.getIntentSource())) {
790                 deleteIntentInstance(intentInstance.getBusinessInstanceId());
791             } else {
792                 resourceMgtService.terminateSlicingService(intentInstance.getBusinessInstanceId());
793             }
794
795
796             tx = session.beginTransaction();
797             session.delete(intentInstance);
798             tx.commit();
799             logger.info("delete IntentInstance OK, id=" + intentInstance.getId());
800         } catch (Exception e) {
801             if(tx!=null){
802                 tx.rollback();
803             }
804             logger.error("delete IntentInstance occur exception:"+e);
805
806         } finally {
807             session.close();
808         }
809     }
810
811     @Override
812     public void verifyIntent(int id) {
813         Session session = getSession();
814         IntentInstance instance = new IntentInstance();
815         try {
816             String hql = "from IntentInstance where id = :id";
817             Query query = session.createQuery(hql).setParameter("id", id);
818             instance = (IntentInstance) query.uniqueResult();
819
820         } catch (Exception e) {
821             logger.error("verifyIntentInstance error. Details:" + e.getMessage());
822         } finally {
823             session.close();
824         }
825     }
826
827     @Override
828     public Page<IntentInstance> getIntentInstanceList(int currentPage, int pageSize) {
829         Page<IntentInstance> page = new Page<IntentInstance>();
830         int allRow = getIntentInstanceAllCount();
831         int offset = page.countOffset(currentPage, pageSize);
832         Session session = getSession();
833         try{
834             String hql = "from IntentInstance order by id";
835             Query query = session.createQuery(hql);
836             query.setFirstResult(offset);
837             query.setMaxResults(pageSize);
838             List<IntentInstance> list= query.list();
839             page.setPageNo(currentPage);
840             page.setPageSize(pageSize);
841             page.setTotalRecords(allRow);
842             page.setList(list);
843             return page;
844         } catch (Exception e) {
845             logger.error("exception occurred while performing IntentInstanceServiceImpl getIntentInstanceList. Details:" + e.getMessage());
846             return null;
847         } finally {
848             session.close();
849         }
850     }
851
852     @Override
853     public ServiceResult createSlicingServiceWithIntent(Object slicingOrderBody) {
854
855         SlicingOrder slicingOrder = JSONObject.parseObject(JSONObject.toJSONString(slicingOrderBody), SlicingOrder.class);
856         ServiceResult serviceResult = slicingService.createSlicingService(slicingOrder);
857         ServiceCreateResult createResult = (ServiceCreateResult) serviceResult.getResult_body();
858
859         createIntentInstance(slicingOrderBody,createResult.getService_id(), slicingOrder.getSlicing_order_info().getName(), IntentConstant.MODEL_TYPE_5GS);
860         return serviceResult;
861     }
862
863     @Override
864     public int updateCCVPNInstance(CCVPNInstance instance) {
865         Session session = getSession();
866         Transaction tx = null;
867         try{
868             if (null == instance){
869                 logger.error("instance is null!");
870                 return 0;
871             }
872             instance.setResourceInstanceId("cll-"+instance.getInstanceId());
873
874             CCVPNInstance ccvpnInstance = (CCVPNInstance)session.createQuery("from CCVPNInstance where instanceId = :instanceId")
875                     .setParameter("instanceId", instance.getInstanceId()).uniqueResult();
876             ccvpnInstance.setAccessPointOneBandWidth(instance.getAccessPointOneBandWidth());
877             saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + ccvpnInstance.getInstanceId(), ccvpnInstance);
878
879             tx = session.beginTransaction();
880             session.update(ccvpnInstance);
881             tx.commit();
882             return 1;
883         } catch (Exception e) {
884             if (tx != null) {
885                 tx.rollback();
886             }
887             logger.error("Details:" + e.getMessage());
888             return 0;
889         } finally {
890             session.close();
891         }
892     }
893
894     public int getIntentInstanceAllCount() {
895         Session session = getSession();
896         try{
897             String count="select count(*) from IntentInstance";
898             Query query = session.createQuery(count);
899             long q=(long)query.uniqueResult();
900             return (int)q;
901         } catch (Exception e) {
902             logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
903             return -1;
904         } finally {
905             session.close();
906         }
907     }
908
909     public void addSubscription() throws IOException {
910         Properties environment = getProperties();
911         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
912         String serviceType = environment.getProperty("ccvpn.serviceType");
913         Response<JSONObject> querySubscription = intentApiService.querySubscription(globalCustomerId, serviceType).execute();
914         if (querySubscription.isSuccessful()) {
915             return;
916         }
917         Map<String, Object> params = new HashMap<>();
918         params.put("service-type", serviceType);
919         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
920         intentApiService.addSubscription(globalCustomerId, serviceType, requestBody).execute();
921     }
922
923     public Properties getProperties() throws IOException {
924         String slicingPath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "ccvpn.properties";
925         InputStream inputStream = new FileInputStream(new File(slicingPath));
926         Properties environment = new Properties();
927         environment.load(inputStream);
928         return environment;
929     }
930
931
932     public void saveIntentInstanceToAAI(String serviceInstanceId, CCVPNInstance instance) throws IOException {
933         addCustomer();
934         addSubscription();
935         Properties environment = getProperties();
936         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
937         String serviceType = environment.getProperty("ccvpn.serviceType");
938         String resourceVersion = null;
939         if (serviceInstanceId != null) {
940             Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
941             if (queryServiceInstance.isSuccessful()) {
942                 JSONObject body = queryServiceInstance.body();
943                 resourceVersion  = body.getString("resource-version");
944             }
945         } else {
946             serviceInstanceId = IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId();
947         }
948         JSONObject environmentContext = JSONObject.parseObject(JSONObject.toJSONString(instance));
949         environmentContext.put("resourceInstanceId",instance.getResourceInstanceId());
950
951         Map<String, Object> params = new HashMap<>();
952         params.put("service-instance-id", serviceInstanceId);
953         params.put("service-instance-name", instance.getName());
954         params.put("service-type", IntentConstant.MODEL_TYPE_CCVPN);
955         params.put("environment-context", environmentContext.toJSONString());
956         params.put("service-instance-location-id", instance.getResourceInstanceId());
957         params.put("bandwidth-total", instance.getAccessPointOneBandWidth());
958         params.put("data-owner", IntentConstant.INTENT_INSTANCE_DATA_OWNER);
959         if (resourceVersion != null) {
960             params.put("resource-version",resourceVersion);
961         }
962         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
963         intentApiService.saveServiceInstance(globalCustomerId,serviceType,serviceInstanceId,requestBody).execute();
964
965     }
966     public void deleteIntentInstanceToAAI(String serviceInstanceId) throws IOException {
967         addCustomer();
968         addSubscription();
969         Properties environment = getProperties();
970         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
971         String serviceType = environment.getProperty("ccvpn.serviceType");
972         if (serviceInstanceId == null) {
973             return;
974         }
975         Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
976         if (queryServiceInstance.isSuccessful()) {
977             JSONObject body = queryServiceInstance.body();
978             String resourceVersion  = body.getString("resource-version");
979             intentApiService.deleteServiceInstance(globalCustomerId,serviceType,serviceInstanceId,resourceVersion).execute();
980         }
981     }
982
983 }