af8955a1a415ea8bef05723a7ed2c298efa49c94
[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             }else {
419                 logger.debug("get Intent-Instance metadatum ok: instance id:" + instance.getInstanceId() + ", metadatum info:" + metadatumResponse.toString());
420             }
421             JSONObject metadatum = metadatumResponse.body();
422             JSONArray metadatumArr = metadatum.getJSONArray("metadatum");
423             int metaval = -1;
424             for (int i = 0; i < metadatumArr.size(); i++) {
425                 if (metaval == -1 || metaval > metadatumArr.getJSONObject(i).getIntValue("metaval")) {
426                     metaval = metadatumArr.getJSONObject(i).getIntValue("metaval");
427                 }
428             }
429             instancePerformance.setBandwidth(metaval);
430
431             Session session = getSession();
432             Transaction tx = null;
433             try{
434                 tx = session.beginTransaction();
435                 session.save(instancePerformance);
436                 tx.commit();
437             } catch (Exception e) {
438                 if(tx!=null){
439                     tx.rollback();
440                 }
441                 logger.error("Details:" + e.getMessage());
442             } finally {
443                 session.close();
444             }
445
446
447         }
448     }
449
450     @Override
451     public void deleteIntentInstance(String instanceId) {
452         CCVPNInstance result = null;
453         Session session = getSession();
454         try {
455
456             result = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
457                     .setParameter("instanceId", instanceId).uniqueResult();
458             logger.info("get CCVPNInstance OK, id=" + instanceId);
459
460         } catch (Exception e) {
461             logger.error("getodel occur exception:"+e);
462
463         } finally {
464             session.close();
465         }
466         try {
467             String serviceInstanceId = result.getResourceInstanceId();
468             deleteInstanceToSO(serviceInstanceId);
469             deleteIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-"+instanceId);
470             deleteInstance(result);
471         }catch (Exception e) {
472             logger.error("delete instance to SO error :" + e);
473         }
474     }
475
476
477     private void deleteInstanceToSO(String serviceInstanceId) throws IOException {
478         JSONObject params = new JSONObject();
479         params.put("serviceInstanceID", serviceInstanceId);
480         params.put("globalSubscriberId", "IBNCustomer");
481         params.put("subscriptionServiceType", "IBN");
482         params.put("serviceType", "CLL");
483         JSONObject additionalProperties = new JSONObject();
484         additionalProperties.put("enableSdnc", "true");
485         params.put("additionalProperties", additionalProperties);
486         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
487         intentApiService.deleteIntentInstance(requestBody).execute();
488     }
489     private String deleteInstance(CCVPNInstance instance) {
490         Transaction tx = null;
491         String result="0";
492         Session session = getSession();
493         try {
494             tx = session.beginTransaction();
495
496             session.delete(instance);
497             tx.commit();
498             logger.info("delete instance OK, id=" + instance.getInstanceId());
499
500             result="1";
501         } catch (Exception e) {
502             if(tx!=null){
503                 tx.rollback();
504             }
505             logger.error("delete instance occur exception:"+e);
506
507         } finally {
508             session.close();
509         }
510         return result;
511     }
512
513     @Override
514     public void activeIntentInstance(String instanceId) {
515         CCVPNInstance instance = null;
516         Session session = getSession();
517         Transaction tx = null;
518         try {
519
520             instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId and status = :status")
521                     .setParameter("instanceId", instanceId).setParameter("status", "3").uniqueResult();
522             logger.info("get instance OK, id=" + instanceId);
523
524             if (null == instance) {
525                 logger.error("instance is null!");
526                 return;
527             }
528
529             String jobId = createIntentInstanceToSO(instance);
530             instance.setStatus("0");
531             instance.setJobId(jobId);
532             tx = session.beginTransaction();
533             session.save(instance);
534             tx.commit();
535
536         }catch (Exception e) {
537             if(tx!=null){
538                 tx.rollback();
539             }
540             logger.error("active instance to SO error :" + e);
541         } finally {
542             session.close();
543         }
544     }
545
546     public void invalidIntentInstance(String instanceId) {
547         CCVPNInstance instance = null;
548         Session session = getSession();
549         Transaction tx = null;
550         try {
551             instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
552                     .setParameter("instanceId", instanceId).uniqueResult();
553             logger.info("get instance OK, id=" + instanceId);
554
555             if (null == instance) {
556                 logger.error("instance is null!");
557                 return;
558             }
559             deleteInstanceToSO(instance.getInstanceId());
560             instance.setStatus("3");
561             tx = session.beginTransaction();
562             session.save(instance);
563             session.flush();
564             tx.commit();
565
566         }catch (Exception e) {
567             if(tx!=null){
568                 tx.rollback();
569             }
570             logger.error("invalid instance to SO error :" + e);
571         } finally {
572             session.close();
573         }
574     }
575
576     @Override
577     public Map<String, Object> queryInstancePerformanceData(String instanceId) {
578         Session session = getSession();
579         try {
580             String hql = "from CCVPNInstance i, InstancePerformance p where i.resourceInstanceId = p.resourceInstanceId and  i.instanceId = :instanceId and i.deleteState = 0 order by p.date";
581             Query query = session.createQuery(hql).setParameter("instanceId", instanceId);
582             List<Object[]> queryResult= query.list();
583             List<String> date = new ArrayList<>();
584             List<Integer> bandwidth = new ArrayList<>();
585             List<Integer> maxBandwidth = new ArrayList<>();
586             SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
587             for (int i = queryResult.size() > 50? queryResult.size() - 50 : 0; i < queryResult.size(); i++) {
588                 Object[] o = queryResult.get(i);
589                 InstancePerformance performance = (InstancePerformance) o[1];
590                 date.add(ft.format(performance.getDate()));
591                 bandwidth.add(performance.getBandwidth());
592                 maxBandwidth.add(performance.getMaxBandwidth());
593             }
594             Map<String, Object> xAxis = new HashMap<>();
595             xAxis.put("data",date);
596             Map<String, Object> bandwidthData = new HashMap<>();
597             bandwidthData.put("data",bandwidth);
598             Map<String, Object> maxBandwidthData = new HashMap<>();
599             maxBandwidthData.put("data",maxBandwidth);
600             List<Map<String, Object>> series = new ArrayList<>();
601             series.add(bandwidthData);
602             series.add(maxBandwidthData);
603
604             Map<String, Object> result = new HashMap<>();
605             result.put("xAxis", xAxis);
606             result.put("series", series);
607
608             return result;
609         }catch (Exception e) {
610             logger.error("invalid instance to SO error :" + e);
611             throw e;
612         } finally {
613             session.close();
614         }
615     }
616
617     @Override
618     public Object queryAccessNodeInfo() throws IOException {
619         Map<String, Object> result = new HashMap<>();
620         List<String> accessNodeList = new ArrayList<>();
621         List<String> cloudAccessNodeList = new ArrayList<>();
622         Response<JSONObject> response = intentApiService.queryNetworkRoute().execute();
623         if (!response.isSuccessful()) {
624             logger.error(response.toString());
625             throw new RuntimeException("Query Access Node Info Error");
626         }
627         JSONObject body = response.body();
628         JSONArray data = body.getJSONArray("network-route");
629         for (int i = 0; i<data.size(); i++) {
630             JSONObject nodeInfo = data.getJSONObject(i);
631             if ("ROOT".equals(nodeInfo.getString("type"))) {
632                 cloudAccessNodeList.add(nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
633             }
634             else {
635                 accessNodeList.add(nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
636             }
637             IntentConstant.NetWorkNodeAlias.put(nodeInfo.getString("route-id"), nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
638         }
639         result.put("accessNodeList",accessNodeList);
640         result.put("cloudAccessNodeList",cloudAccessNodeList);
641         return result;
642     }
643
644     @Override
645     public JSONObject getInstanceStatus(JSONArray ids) {
646         Session session = getSession();
647         try {
648             JSONObject result = new JSONObject();
649             JSONArray instanceInfos = new JSONArray();
650             String hql = "from CCVPNInstance i where i.instanceId in (:ids)";
651             Query query = session.createQuery(hql).setParameter("ids", ids);
652             List<CCVPNInstance> queryResult= query.list();
653             if (queryResult != null && queryResult.size() > 0) {
654                 for (CCVPNInstance instance : queryResult) {
655                     JSONObject instanceInfo = new JSONObject();
656                     instanceInfo.put("id", instance.getInstanceId());
657                     instanceInfo.put("status", instance.getStatus());
658                     instanceInfos.add(instanceInfo);
659                 }
660             }
661             result.put("IntentInstances",instanceInfos);
662             return result;
663
664         } catch (Exception e) {
665             logger.error("get Instance status error : " + e.getMessage());
666             throw e;
667         } finally {
668             session.close();
669         }
670     }
671
672
673     public String formatBandwidth(String strValue) {
674         String ret;
675         Pattern pattern = Pattern.compile("(\\d+)([\\w ]*)");
676         Matcher matcher = pattern.matcher(strValue);
677
678
679         int dataRate = 100;
680         if (matcher.matches()) {
681             dataRate = Integer.parseInt(matcher.group(1));
682             String company = matcher.group(2).trim().toLowerCase();
683             if (GB_COMPANY.contains(company)) {
684                 dataRate = dataRate * 1000;
685             }
686             else if (!MB_COMPANY.contains(company)) {
687                 dataRate = 100;
688             }
689             dataRate = dataRate < MIN_BANDWIDTH ? MIN_BANDWIDTH : (dataRate > MAX_BANDWIDTH ? MAX_BANDWIDTH : dataRate);
690         }
691         ret = dataRate + "";
692         return ret;
693     }
694
695
696     public String formatCloudPoint(String cloudPoint) {
697         String cloudPointAlias = "";
698         switch (cloudPoint) {
699             case "Cloud one" :
700                 cloudPointAlias = "tranportEp_dst_ID_212_1";
701                 break;
702         }
703         return cloudPointAlias;
704     }
705
706     public String formatAccessPoint(String accessPoint) {
707         String accessPointAlias = "";
708         switch (accessPoint) {
709             case "Access one" :
710                 accessPointAlias = "tranportEp_src_ID_111_1";
711                 break;
712             case "Access two" :
713                 accessPointAlias = "tranportEp_src_ID_111_2";
714                 break;
715             case "Access three" :
716                 accessPointAlias = "tranportEp_src_ID_113_1";
717                 break;
718         }
719         return accessPointAlias;
720     }
721
722     public void addCustomer() throws IOException {
723         Properties environment = getProperties();
724         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
725         Response<JSONObject> queryCustomerResponse = intentApiService.queryCustomer(globalCustomerId).execute();
726         if (queryCustomerResponse.isSuccessful()) {
727             return;
728         }
729         String subscriberName = environment.getProperty("ccvpn.subscriberName");
730         String subscriberType = environment.getProperty("ccvpn.subscriberType");
731         Map<String, Object> params = new HashMap<>();
732         params.put("global-customer-id", globalCustomerId);
733         params.put("subscriber-name", subscriberName);
734         params.put("subscriber-type", subscriberType);
735         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
736         intentApiService.addCustomer(globalCustomerId, requestBody).execute();
737     }
738
739     @Override
740     public IntentInstance createIntentInstance(Object body,String businessInstanceId, String businessInstance, String type) {
741         IntentInstance instance = new IntentInstance();
742         if (IntentConstant.MODEL_TYPE_CCVPN.equals(type)) {
743             assembleIntentInstanceFormCCVPNInfo(instance, body);
744         }
745         else if (IntentConstant.MODEL_TYPE_5GS.equals(type)) {
746             assembleIntentInstanceFormSliceInfo(instance, body);
747         }
748         instance.setIntentSource(type);
749         instance.setBusinessInstanceId(businessInstanceId);
750         instance.setBusinessInstance(businessInstance);
751         Session session = getSession();
752         Transaction tx = null;
753         try{
754             tx = session.beginTransaction();
755             session.save(instance);
756             tx.commit();
757             return instance;
758         } catch (Exception e) {
759             if (tx != null) {
760                 tx.rollback();
761             }
762             logger.error("createIntentInstance Details:" + e.getMessage());
763             return null;
764         } finally {
765             session.close();
766         }
767     }
768
769     private IntentInstance assembleIntentInstanceFormCCVPNInfo(IntentInstance instance, Object body) {
770         JSONObject jsonObject = new JSONObject((Map) body);
771         String intent_content = jsonObject.getString("intentContent");
772         jsonObject.remove("intentContent");
773         instance.setIntentConfig(jsonObject.toJSONString());
774         instance.setIntentContent(intent_content);
775         instance.setIntentName(jsonObject.getString("name"));
776         return instance;
777     }
778
779     private IntentInstance assembleIntentInstanceFormSliceInfo(IntentInstance instance, Object body) {
780         JSONObject jsonObject = new JSONObject((Map) body);
781         JSONObject slicingOrderInfo = jsonObject.getJSONObject("slicing_order_info");
782         String intent_content = slicingOrderInfo.getString("intentContent");
783         slicingOrderInfo.remove("intentContent");
784         instance.setIntentConfig(slicingOrderInfo.toJSONString());
785         instance.setIntentContent(intent_content);
786         instance.setIntentName(slicingOrderInfo.getString("name"));
787         return instance;
788     }
789
790
791     @Override
792     public void deleteIntent(int id) {
793         Transaction tx = null;
794         Session session = getSession();
795         try {
796             IntentInstance intentInstance = (IntentInstance)session.createQuery("from IntentInstance where id = :id")
797                     .setParameter("id", id).uniqueResult();
798             if (IntentConstant.MODEL_TYPE_CCVPN.equals(intentInstance.getIntentSource())) {
799                 deleteIntentInstance(intentInstance.getBusinessInstanceId());
800             } else {
801                 resourceMgtService.terminateSlicingService(intentInstance.getBusinessInstanceId());
802             }
803
804
805             tx = session.beginTransaction();
806             session.delete(intentInstance);
807             tx.commit();
808             logger.info("delete IntentInstance OK, id=" + intentInstance.getId());
809         } catch (Exception e) {
810             if(tx!=null){
811                 tx.rollback();
812             }
813             logger.error("delete IntentInstance occur exception:"+e);
814
815         } finally {
816             session.close();
817         }
818     }
819
820     @Override
821     public void verifyIntent(int id) {
822         Session session = getSession();
823         IntentInstance instance = new IntentInstance();
824         try {
825             String hql = "from IntentInstance where id = :id";
826             Query query = session.createQuery(hql).setParameter("id", id);
827             instance = (IntentInstance) query.uniqueResult();
828
829         } catch (Exception e) {
830             logger.error("verifyIntentInstance error. Details:" + e.getMessage());
831         } finally {
832             session.close();
833         }
834     }
835
836     @Override
837     public Page<IntentInstance> getIntentInstanceList(int currentPage, int pageSize) {
838         Page<IntentInstance> page = new Page<IntentInstance>();
839         int allRow = getIntentInstanceAllCount();
840         int offset = page.countOffset(currentPage, pageSize);
841         Session session = getSession();
842         try{
843             String hql = "from IntentInstance order by id";
844             Query query = session.createQuery(hql);
845             query.setFirstResult(offset);
846             query.setMaxResults(pageSize);
847             List<IntentInstance> list= query.list();
848             page.setPageNo(currentPage);
849             page.setPageSize(pageSize);
850             page.setTotalRecords(allRow);
851             page.setList(list);
852             return page;
853         } catch (Exception e) {
854             logger.error("exception occurred while performing IntentInstanceServiceImpl getIntentInstanceList. Details:" + e.getMessage());
855             return null;
856         } finally {
857             session.close();
858         }
859     }
860
861     @Override
862     public ServiceResult createSlicingServiceWithIntent(Object slicingOrderBody) {
863
864         SlicingOrder slicingOrder = JSONObject.parseObject(JSONObject.toJSONString(slicingOrderBody), SlicingOrder.class);
865         ServiceResult serviceResult = slicingService.createSlicingService(slicingOrder);
866         ServiceCreateResult createResult = (ServiceCreateResult) serviceResult.getResult_body();
867
868         createIntentInstance(slicingOrderBody,createResult.getService_id(), slicingOrder.getSlicing_order_info().getName(), IntentConstant.MODEL_TYPE_5GS);
869         return serviceResult;
870     }
871
872     @Override
873     public int updateCCVPNInstance(CCVPNInstance instance) {
874         Session session = getSession();
875         Transaction tx = null;
876         try{
877             if (null == instance){
878                 logger.error("instance is null!");
879                 return 0;
880             }
881             instance.setResourceInstanceId("cll-"+instance.getInstanceId());
882
883             CCVPNInstance ccvpnInstance = (CCVPNInstance)session.createQuery("from CCVPNInstance where instanceId = :instanceId")
884                     .setParameter("instanceId", instance.getInstanceId()).uniqueResult();
885             ccvpnInstance.setAccessPointOneBandWidth(instance.getAccessPointOneBandWidth());
886             saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + ccvpnInstance.getInstanceId(), ccvpnInstance);
887
888             tx = session.beginTransaction();
889             session.update(ccvpnInstance);
890             tx.commit();
891             return 1;
892         } catch (Exception e) {
893             if (tx != null) {
894                 tx.rollback();
895             }
896             logger.error("Details:" + e.getMessage());
897             return 0;
898         } finally {
899             session.close();
900         }
901     }
902
903     public int getIntentInstanceAllCount() {
904         Session session = getSession();
905         try{
906             String count="select count(*) from IntentInstance";
907             Query query = session.createQuery(count);
908             long q=(long)query.uniqueResult();
909             return (int)q;
910         } catch (Exception e) {
911             logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
912             return -1;
913         } finally {
914             session.close();
915         }
916     }
917
918     public void addSubscription() throws IOException {
919         Properties environment = getProperties();
920         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
921         String serviceType = environment.getProperty("ccvpn.serviceType");
922         Response<JSONObject> querySubscription = intentApiService.querySubscription(globalCustomerId, serviceType).execute();
923         if (querySubscription.isSuccessful()) {
924             return;
925         }
926         Map<String, Object> params = new HashMap<>();
927         params.put("service-type", serviceType);
928         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
929         intentApiService.addSubscription(globalCustomerId, serviceType, requestBody).execute();
930     }
931
932     public Properties getProperties() throws IOException {
933         String slicingPath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "ccvpn.properties";
934         InputStream inputStream = new FileInputStream(new File(slicingPath));
935         Properties environment = new Properties();
936         environment.load(inputStream);
937         return environment;
938     }
939
940
941     public void saveIntentInstanceToAAI(String serviceInstanceId, CCVPNInstance instance) throws IOException {
942         addCustomer();
943         addSubscription();
944         Properties environment = getProperties();
945         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
946         String serviceType = environment.getProperty("ccvpn.serviceType");
947         String resourceVersion = null;
948         if (serviceInstanceId != null) {
949             Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
950             if (queryServiceInstance.isSuccessful()) {
951                 JSONObject body = queryServiceInstance.body();
952                 resourceVersion  = body.getString("resource-version");
953             }
954         } else {
955             serviceInstanceId = IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId();
956         }
957         JSONObject environmentContext = JSONObject.parseObject(JSONObject.toJSONString(instance));
958         environmentContext.put("resourceInstanceId",instance.getResourceInstanceId());
959
960         Map<String, Object> params = new HashMap<>();
961         params.put("service-instance-id", serviceInstanceId);
962         params.put("service-instance-name", instance.getName());
963         params.put("service-type", IntentConstant.MODEL_TYPE_CCVPN);
964         params.put("environment-context", environmentContext.toJSONString());
965         params.put("service-instance-location-id", instance.getResourceInstanceId());
966         params.put("bandwidth-total", instance.getAccessPointOneBandWidth());
967         params.put("data-owner", IntentConstant.INTENT_INSTANCE_DATA_OWNER);
968         if (resourceVersion != null) {
969             params.put("resource-version",resourceVersion);
970         }
971         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
972         intentApiService.saveServiceInstance(globalCustomerId,serviceType,serviceInstanceId,requestBody).execute();
973
974     }
975     public void deleteIntentInstanceToAAI(String serviceInstanceId) throws IOException {
976         addCustomer();
977         addSubscription();
978         Properties environment = getProperties();
979         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
980         String serviceType = environment.getProperty("ccvpn.serviceType");
981         if (serviceInstanceId == null) {
982             return;
983         }
984         Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
985         if (queryServiceInstance.isSuccessful()) {
986             JSONObject body = queryServiceInstance.body();
987             String resourceVersion  = body.getString("resource-version");
988             intentApiService.deleteServiceInstance(globalCustomerId,serviceType,serviceInstanceId,resourceVersion).execute();
989         }
990     }
991
992 }