aboutsummaryrefslogtreecommitdiffstats
path: root/server/src/main/java/org/onap/usecaseui/server/service/intent/impl/IntentInstanceServiceImpl.java
blob: c47cdc1501f2a2a9499febc5a7ccc8a1c945cdfb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
/*
 * Copyright (C) 2021 CTC, Inc. and others. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.onap.usecaseui.server.service.intent.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.onap.usecaseui.server.bean.csmf.ServiceCreateResult;
import org.onap.usecaseui.server.bean.csmf.SlicingOrder;
import org.onap.usecaseui.server.bean.csmf.SlicingOrderDetail;
import org.onap.usecaseui.server.bean.intent.InstancePerformance;
import org.onap.usecaseui.server.bean.intent.CCVPNInstance;
import org.onap.usecaseui.server.bean.intent.IntentInstance;
import org.onap.usecaseui.server.bean.nsmf.common.ServiceResult;
import org.onap.usecaseui.server.constant.IntentConstant;
import org.onap.usecaseui.server.service.csmf.SlicingService;
import org.onap.usecaseui.server.service.intent.IntentApiService;
import org.onap.usecaseui.server.service.intent.IntentInstanceService;
import org.onap.usecaseui.server.service.lcm.domain.so.SOService;
import org.onap.usecaseui.server.service.nsmf.ResourceMgtService;
import org.onap.usecaseui.server.util.Page;
import org.onap.usecaseui.server.util.RestfulServices;
import org.onap.usecaseui.server.util.UuiCommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Service;
import retrofit2.Call;
import retrofit2.Response;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service("IntentInstanceService")
@Transactional
@org.springframework.context.annotation.Configuration
@EnableAspectJAutoProxy
public class IntentInstanceServiceImpl implements IntentInstanceService {
    private static final Logger logger = LoggerFactory.getLogger(IntentInstanceServiceImpl.class);

    @Autowired
    private SessionFactory sessionFactory;

    @Resource(name = "ResourceMgtService")
    private ResourceMgtService resourceMgtService;

    @Resource(name = "SlicingService")
    private SlicingService slicingService;

    private IntentApiService intentApiService;

    private SOService soService;

    private final static int MAX_BANDWIDTH = 6000;
    private final static int MIN_BANDWIDTH = 100;

    private final static List<String> GB_COMPANY = Arrays.asList(new String[] {"gbps", "gb"});
    private final static List<String> MB_COMPANY = Arrays.asList(new String[] {"mbps", "mb"});

    public IntentInstanceServiceImpl() {
        this(RestfulServices.create(IntentApiService.class),RestfulServices.create(SOService.class));
    }
    public IntentInstanceServiceImpl(IntentApiService intentApiService, SOService soService) {
        this.intentApiService = intentApiService;
        this.soService = soService;
    }

    private Session getSession() {
        return sessionFactory.openSession();
    }

    @Override
    public Page<CCVPNInstance> queryIntentInstance(CCVPNInstance instance, int currentPage, int pageSize) {
        Page<CCVPNInstance> page = new Page<CCVPNInstance>();
        int allRow =this.getAllCount(instance,currentPage,pageSize);
        int offset = page.countOffset(currentPage, pageSize);
        Session session = getSession();
        try{
            StringBuffer hql =new StringBuffer("from CCVPNInstance a where deleteState = 0");
            if (null != instance) {
                if(UuiCommonUtil.isNotNullOrEmpty(instance.getInstanceId())) {
                    String ver =instance.getInstanceId();
                    hql.append(" and a.instance_id = '"+ver+"'");
                }
                if(UuiCommonUtil.isNotNullOrEmpty(instance.getJobId())) {
                    String ver =instance.getJobId();
                    hql.append(" and a.job_id = '"+ver+"'");
                }
                if(UuiCommonUtil.isNotNullOrEmpty(instance.getStatus())) {
                    String ver =instance.getStatus();
                    hql.append(" and a.status = '"+ver+"'");
                }
            }
            hql.append(" order by id");
            logger.info("AlarmsHeaderServiceImpl queryIntentInstance: instance={}", instance);
            Query query = session.createQuery(hql.toString());
            query.setFirstResult(offset);
            query.setMaxResults(pageSize);
            List<CCVPNInstance> list= query.list();
            page.setPageNo(currentPage);
            page.setPageSize(pageSize);
            page.setTotalRecords(allRow);
            page.setList(list);
            return page;
        } catch (Exception e) {
            logger.error("exception occurred while performing AlarmsHeaderServiceImpl queryAlarmsHeader. Details:" + e.getMessage());
            return null;
        } finally {
            session.close();
        }
    }


    public int getAllCount(CCVPNInstance instance, int currentPage, int pageSize) {
        Session session = getSession();
        try{
            StringBuffer count=new StringBuffer("select count(*) from CCVPNInstance a where deleteState = 0");
            if (null != instance) {
                if(UuiCommonUtil.isNotNullOrEmpty(instance.getInstanceId())) {
                    String ver =instance.getInstanceId();
                    count.append(" and a.instance_id = '"+ver+"'");
                }
                if(UuiCommonUtil.isNotNullOrEmpty(instance.getJobId())) {
                    String ver =instance.getJobId();
                    count.append(" and a.job_id = '"+ver+"'");
                }
                if(UuiCommonUtil.isNotNullOrEmpty(instance.getStatus())) {
                    String ver =instance.getStatus();
                    count.append(" and a.status = '"+ver+"'");
                }
            }
            Query query = session.createQuery(count.toString());
            long q=(long)query.uniqueResult();
            return (int)q;
        } catch (Exception e) {
            logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
            return -1;
        } finally {
            session.close();
        }
    }

    @Override
    public int createCCVPNInstance(CCVPNInstance instance) {
        Session session = getSession();
        Transaction tx = null;
        try{

            if (null == instance){
                logger.error("instance is null!");
                return 0;
            }
            String jobId = createIntentInstanceToSO(instance);
            if (null == jobId){
                logger.error("create Instance error:jobId is null");
                return 0;
            }
            instance.setJobId(jobId);
            instance.setResourceInstanceId("cll-"+instance.getInstanceId());
            saveIntentInstanceToAAI(null, instance);

            tx = session.beginTransaction();
            session.save(instance);
            tx.commit();
            return 1;
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            logger.error("Details:" + e.getMessage());
            return 0;
        } finally {
            session.close();
        }
    }

    public String createIntentInstanceToSO(CCVPNInstance instance) throws IOException {
        Map<String, Object> params = new HashMap<>();
        params.put("name", instance.getName());
        params.put("modelInvariantUuid", "6790ab0e-034f-11eb-adc1-0242ac120002");
        params.put("modelUuid", "6790ab0e-034f-11eb-adc1-0242ac120002");
        params.put("globalSubscriberId", "IBNCustomer");
        params.put("subscriptionServiceType", "IBN");
        params.put("serviceType", "CLL");
        Map<String, Object> additionalProperties = new HashMap<>();
        additionalProperties.put("enableSdnc", "true");
        additionalProperties.put("serviceInstanceID", "cll-" + instance.getInstanceId());
        List<Map<String, Object>> transportNetworks = new ArrayList<>();
        Map<String, Object> transportNetwork = new HashMap<>();
        transportNetwork.put("id", "");
        Map<String, Object> sla = new HashMap<>();
        sla.put("latency", "2");
        sla.put("maxBandwidth", instance.getAccessPointOneBandWidth());
        List<Map<String, Object>> connectionLinks = new ArrayList<>();
        Map<String, Object> connectionLink = new HashMap<>();
        connectionLink.put("name", "");
        connectionLink.put("transportEndpointA", instance.getAccessPointOneName());
        connectionLink.put("transportEndpointB", instance.getCloudPointName());
        connectionLinks.add(connectionLink);
        if (instance.getProtectStatus() == 1) {
            sla.put("protectionType", instance.getProtectionType());
            connectionLink.put("transportEndpointBProtection", instance.getProtectionCloudPointName());
        }
        transportNetwork.put("sla", sla);
        transportNetwork.put("connectionLinks", connectionLinks);
        transportNetworks.add(transportNetwork);
        additionalProperties.put("transportNetworks", transportNetworks);
        params.put("additionalProperties",additionalProperties);

        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
        Response<JSONObject> response = intentApiService.createIntentInstance(requestBody).execute();
        if (response.isSuccessful()) {
            return response.body().getString("jobId");
        }
        return null;
    }

    @Override
    public void getIntentInstanceProgress() {
        List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("0");
        for (CCVPNInstance instance: instanceList) {
            try {

                int progress = getProgressByJobId(instance);
                instance.setProgress(progress);
                if (progress >=100) {
                    instance.setStatus("1");
                    saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId(),instance);
                }
            }
            catch (Exception e) {
                logger.info("get progress exception:"+e);
            }
        }
        saveProgress(instanceList);

    }
    @Override
    public void getIntentInstanceCreateStatus() {
        List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("0");
        for (CCVPNInstance instance: instanceList) {
            try {

                int flag = getCreateStatusByJobId(instance);
                if (flag > 0) {
                    instance.setStatus(flag + "");
                    saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId(),instance);
                }
            }
            catch (Exception e) {
                logger.info("get progress exception:"+e);
            }
        }
        saveProgress(instanceList);

    }

    private void saveProgress(List<CCVPNInstance> instanceList) {
        if(instanceList == null || instanceList.isEmpty()) {
            return;
        }
        Session session = getSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            for (CCVPNInstance instance : instanceList) {
                session.update(instance);
                session.flush();
            }
            tx.commit();
            logger.info("update progress ok");

        } catch (Exception e) {
            if(tx!=null){
                tx.rollback();
            }
            logger.error("update progress exception:"+e);

        } finally {
            session.close();
        }
    }

    private int getProgressByJobId(CCVPNInstance instance) throws IOException {
        Response<JSONObject> response = intentApiService.queryOperationProgress(instance.getResourceInstanceId(), instance.getJobId()).execute();
        logger.debug(response.toString());
        if (response.isSuccessful()) {
            if (response.body().containsKey("operation")) {
                return response.body().getJSONObject("operation").getInteger("progress");
            }
        }
        return -1;
    }

    private int getCreateStatusByJobId(CCVPNInstance instance) throws IOException {
        if (instance == null || instance.getResourceInstanceId() == null) {
            return -1;
        }
        Response<JSONObject> response = intentApiService.getInstanceInfo(instance.getResourceInstanceId()).execute();
        logger.debug(response.toString());
        if (response.isSuccessful()) {
            String status = response.body().getString("orchestration-status");
            if ("created".equals(status)) {
                return 1;
            }
            return 0;
        }
        logger.error("getIntentInstance Create Statue Error:" + response.toString());
        return -1;
    }

    private List<CCVPNInstance> getInstanceByFinishedFlag(String flag) {
        Session session = getSession();
        try{
            StringBuffer sql=new StringBuffer("from CCVPNInstance where deleteState = 0 and status = '" + flag + "'");

            Query query = session.createQuery(sql.toString());
            List<CCVPNInstance> q=(List<CCVPNInstance>) query.list();
            logger.debug(q.toString());
            return q;
        } catch (Exception e) {
            logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
            return null;
        } finally {
            session.close();
        }
    }


    @Override
    public List<CCVPNInstance> getFinishedInstanceInfo() {
        Session session = getSession();
        try{
            StringBuffer count=new StringBuffer("from CCVPNInstance where status = '1' and deleteState = 0");

            Query query = session.createQuery(count.toString());
            List<CCVPNInstance> q=(List<CCVPNInstance>) query.list();
            logger.debug(q.toString());
            return q;
        } catch (Exception e) {
            logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
            return null;
        } finally {
            session.close();
        }
    }

    @Override
    public void getIntentInstanceBandwidth() throws IOException {
        List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("1");
        for (CCVPNInstance instance : instanceList) {
            String serviceInstanceId = instance.getResourceInstanceId();
            Response<JSONObject> response = intentApiService.getInstanceNetworkInfo(serviceInstanceId).execute();
            if (!response.isSuccessful()) {
                logger.error("get Intent-Instance Bandwidth error:" + response.toString());
                continue;
            }
            JSONObject responseBody = response.body();
            JSONObject allottedResource = responseBody.getJSONObject("allotted-resources").getJSONArray("allotted-resource").getJSONObject(0);
            JSONArray relationshipList = allottedResource.getJSONObject("relationship-list").getJSONArray("relationship");
            String networkPolicyId = null;
            for (int i = 0; i<relationshipList.size();i++) {
                if ("network-policy".equals(relationshipList.getJSONObject(i).getString("related-to"))) {
                    JSONArray datas = relationshipList.getJSONObject(i).getJSONArray("relationship-data");
                    for (int j = 0; j<relationshipList.size();j++) {
                        if ("network-policy.network-policy-id".equals(datas.getJSONObject(j).getString("relationship-key"))) {
                            networkPolicyId = datas.getJSONObject(j).getString("relationship-value");
                            break;
                        }
                    }
                    break;
                }
            }
            if (networkPolicyId== null) {
                logger.error("get network Policy Id exception. serviceInstanceId:" + instance.getResourceInstanceId());
                continue;
            }

            Response<JSONObject> networkPolicyInfoResponse = intentApiService.getInstanceNetworkPolicyInfo(networkPolicyId).execute();
            if (!networkPolicyInfoResponse.isSuccessful()) {
                logger.error("get Intent-Instance networkPolicyInfo error:" + networkPolicyInfoResponse.toString());
                continue;
            }
            JSONObject networkPolicyInfo = networkPolicyInfoResponse.body();
            int maxBandwidth =  networkPolicyInfo.getIntValue("max-bandwidth") * 1000;
            InstancePerformance instancePerformance = new InstancePerformance();
            instancePerformance.setMaxBandwidth(maxBandwidth);
            instancePerformance.setResourceInstanceId(instance.getResourceInstanceId());
            instancePerformance.setJobId(instance.getJobId());
            instancePerformance.setDate(new Date());

            Response<JSONObject> metadatumResponse = intentApiService.getInstanceBandwidth(serviceInstanceId).execute();
            if (!metadatumResponse.isSuccessful()) {
                logger.error("get Intent-Instance metadatum error:" + metadatumResponse.toString());
                continue;
            }else {
                logger.debug("get Intent-Instance metadatum ok: instance id:" + instance.getInstanceId() + ", metadatum info:" + metadatumResponse.toString());
            }
            JSONObject metadatum = metadatumResponse.body();
            JSONArray metadatumArr = metadatum.getJSONArray("metadatum");
            int metaval = -1;
            for (int i = 0; i < metadatumArr.size(); i++) {
                if (metaval == -1 || metaval > metadatumArr.getJSONObject(i).getIntValue("metaval")) {
                    metaval = metadatumArr.getJSONObject(i).getIntValue("metaval");
                }
            }
            instancePerformance.setBandwidth(metaval);

            Session session = getSession();
            Transaction tx = null;
            try{
                tx = session.beginTransaction();
                session.save(instancePerformance);
                tx.commit();
            } catch (Exception e) {
                if(tx!=null){
                    tx.rollback();
                }
                logger.error("Details:" + e.getMessage());
            } finally {
                session.close();
            }


        }
    }

    @Override
    public void deleteIntentInstance(String instanceId) {
        CCVPNInstance result = null;
        Session session = getSession();
        try {

            result = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
                    .setParameter("instanceId", instanceId).uniqueResult();
            logger.info("get CCVPNInstance OK, id=" + instanceId);

        } catch (Exception e) {
            logger.error("getodel occur exception:"+e);

        } finally {
            session.close();
        }
        try {
            String serviceInstanceId = result.getResourceInstanceId();
            deleteInstanceToSO(serviceInstanceId);
            deleteIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-"+instanceId);
            deleteInstance(result);
        }catch (Exception e) {
            logger.error("delete instance to SO error :" + e);
        }
    }


    private void deleteInstanceToSO(String serviceInstanceId) throws IOException {
        JSONObject params = new JSONObject();
        params.put("serviceInstanceID", serviceInstanceId);
        params.put("globalSubscriberId", "IBNCustomer");
        params.put("subscriptionServiceType", "IBN");
        params.put("serviceType", "CLL");
        JSONObject additionalProperties = new JSONObject();
        additionalProperties.put("enableSdnc", "true");
        params.put("additionalProperties", additionalProperties);
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
        intentApiService.deleteIntentInstance(requestBody).execute();
    }
    private String deleteInstance(CCVPNInstance instance) {
        Transaction tx = null;
        String result="0";
        Session session = getSession();
        try {
            tx = session.beginTransaction();

            session.delete(instance);
            tx.commit();
            logger.info("delete instance OK, id=" + instance.getInstanceId());

            result="1";
        } catch (Exception e) {
            if(tx!=null){
                tx.rollback();
            }
            logger.error("delete instance occur exception:"+e);

        } finally {
            session.close();
        }
        return result;
    }

    @Override
    public void activeIntentInstance(String instanceId) {
        CCVPNInstance instance = null;
        Session session = getSession();
        Transaction tx = null;
        try {

            instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId and status = :status")
                    .setParameter("instanceId", instanceId).setParameter("status", "3").uniqueResult();
            logger.info("get instance OK, id=" + instanceId);

            if (null == instance) {
                logger.error("instance is null!");
                return;
            }

            String jobId = createIntentInstanceToSO(instance);
            instance.setStatus("0");
            instance.setJobId(jobId);
            tx = session.beginTransaction();
            session.save(instance);
            tx.commit();

        }catch (Exception e) {
            if(tx!=null){
                tx.rollback();
            }
            logger.error("active instance to SO error :" + e);
        } finally {
            session.close();
        }
    }

    public void invalidIntentInstance(String instanceId) {
        CCVPNInstance instance = null;
        Session session = getSession();
        Transaction tx = null;
        try {
            instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
                    .setParameter("instanceId", instanceId).uniqueResult();
            logger.info("get instance OK, id=" + instanceId);

            if (null == instance) {
                logger.error("instance is null!");
                return;
            }
            deleteInstanceToSO(instance.getInstanceId());
            instance.setStatus("3");
            tx = session.beginTransaction();
            session.save(instance);
            session.flush();
            tx.commit();

        }catch (Exception e) {
            if(tx!=null){
                tx.rollback();
            }
            logger.error("invalid instance to SO error :" + e);
        } finally {
            session.close();
        }
    }

    @Override
    public Map<String, Object> queryInstancePerformanceData(String instanceId) {
        Session session = getSession();
        try {
            String hql = "from CCVPNInstance i, InstancePerformance p where i.resourceInstanceId = p.resourceInstanceId and  i.instanceId = :instanceId and i.deleteState = 0 order by p.date";
            Query query = session.createQuery(hql).setParameter("instanceId", instanceId);
            List<Object[]> queryResult= query.list();
            List<String> date = new ArrayList<>();
            List<Integer> bandwidth = new ArrayList<>();
            List<Integer> maxBandwidth = new ArrayList<>();
            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i = queryResult.size() > 50? queryResult.size() - 50 : 0; i < queryResult.size(); i++) {
                Object[] o = queryResult.get(i);
                InstancePerformance performance = (InstancePerformance) o[1];
                date.add(ft.format(performance.getDate()));
                bandwidth.add(performance.getBandwidth());
                maxBandwidth.add(performance.getMaxBandwidth());
            }
            Map<String, Object> xAxis = new HashMap<>();
            xAxis.put("data",date);
            Map<String, Object> bandwidthData = new HashMap<>();
            bandwidthData.put("data",bandwidth);
            Map<String, Object> maxBandwidthData = new HashMap<>();
            maxBandwidthData.put("data",maxBandwidth);
            List<Map<String, Object>> series = new ArrayList<>();
            series.add(bandwidthData);
            series.add(maxBandwidthData);

            Map<String, Object> result = new HashMap<>();
            result.put("xAxis", xAxis);
            result.put("series", series);

            return result;
        }catch (Exception e) {
            logger.error("invalid instance to SO error :" + e);
            throw e;
        } finally {
            session.close();
        }
    }

    @Override
    public Object queryAccessNodeInfo() throws IOException {
        Map<String, Object> result = new HashMap<>();
        List<String> accessNodeList = new ArrayList<>();
        List<String> cloudAccessNodeList = new ArrayList<>();
        Response<JSONObject> response = intentApiService.queryNetworkRoute().execute();
        if (!response.isSuccessful()) {
            logger.error(response.toString());
            throw new RuntimeException("Query Access Node Info Error");
        }
        JSONObject body = response.body();
        JSONArray data = body.getJSONArray("network-route");
        for (int i = 0; i<data.size(); i++) {
            JSONObject nodeInfo = data.getJSONObject(i);
            if ("ROOT".equals(nodeInfo.getString("type"))) {
                cloudAccessNodeList.add(nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
            }
            else {
                accessNodeList.add(nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
            }
            IntentConstant.NetWorkNodeAlias.put(nodeInfo.getString("route-id"), nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
        }
        result.put("accessNodeList",accessNodeList);
        result.put("cloudAccessNodeList",cloudAccessNodeList);
        return result;
    }

    @Override
    public JSONObject getInstanceStatus(JSONArray ids) {
        Session session = getSession();
        try {
            JSONObject result = new JSONObject();
            JSONArray instanceInfos = new JSONArray();
            String hql = "from CCVPNInstance i where i.instanceId in (:ids)";
            Query query = session.createQuery(hql).setParameter("ids", ids);
            List<CCVPNInstance> queryResult= query.list();
            if (queryResult != null && queryResult.size() > 0) {
                for (CCVPNInstance instance : queryResult) {
                    JSONObject instanceInfo = new JSONObject();
                    instanceInfo.put("id", instance.getInstanceId());
                    instanceInfo.put("status", instance.getStatus());
                    instanceInfos.add(instanceInfo);
                }
            }
            result.put("IntentInstances",instanceInfos);
            return result;

        } catch (Exception e) {
            logger.error("get Instance status error : " + e.getMessage());
            throw e;
        } finally {
            session.close();
        }
    }


    public String formatBandwidth(String strValue) {
        String ret;
        Pattern pattern = Pattern.compile("(\\d+)([\\w ]*)");
        Matcher matcher = pattern.matcher(strValue);


        int dataRate = 100;
        if (matcher.matches()) {
            dataRate = Integer.parseInt(matcher.group(1));
            String company = matcher.group(2).trim().toLowerCase();
            if (GB_COMPANY.contains(company)) {
                dataRate = dataRate * 1000;
            }
            else if (!MB_COMPANY.contains(company)) {
                dataRate = 100;
            }
            dataRate = dataRate < MIN_BANDWIDTH ? MIN_BANDWIDTH : (dataRate > MAX_BANDWIDTH ? MAX_BANDWIDTH : dataRate);
        }
        ret = dataRate + "";
        return ret;
    }


    public String formatCloudPoint(String cloudPoint) {
        String cloudPointAlias = "";
        switch (cloudPoint) {
            case "Cloud one" :
                cloudPointAlias = "tranportEp_dst_ID_212_1";
                break;
        }
        return cloudPointAlias;
    }

    public String formatAccessPoint(String accessPoint) {
        String accessPointAlias = "";
        switch (accessPoint) {
            case "Access one" :
                accessPointAlias = "tranportEp_src_ID_111_1";
                break;
            case "Access two" :
                accessPointAlias = "tranportEp_src_ID_111_2";
                break;
            case "Access three" :
                accessPointAlias = "tranportEp_src_ID_113_1";
                break;
        }
        return accessPointAlias;
    }

    public void addCustomer() throws IOException {
        Properties environment = getProperties();
        String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
        Response<JSONObject> queryCustomerResponse = intentApiService.queryCustomer(globalCustomerId).execute();
        if (queryCustomerResponse.isSuccessful()) {
            return;
        }
        String subscriberName = environment.getProperty("ccvpn.subscriberName");
        String subscriberType = environment.getProperty("ccvpn.subscriberType");
        Map<String, Object> params = new HashMap<>();
        params.put("global-customer-id", globalCustomerId);
        params.put("subscriber-name", subscriberName);
        params.put("subscriber-type", subscriberType);
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
        intentApiService.addCustomer(globalCustomerId, requestBody).execute();
    }

    @Override
    public IntentInstance createIntentInstance(Object body,String businessInstanceId, String businessInstance, String type) {
        IntentInstance instance = new IntentInstance();
        if (IntentConstant.MODEL_TYPE_CCVPN.equals(type)) {
            assembleIntentInstanceFormCCVPNInfo(instance, body);
        }
        else if (IntentConstant.MODEL_TYPE_5GS.equals(type)) {
            assembleIntentInstanceFormSliceInfo(instance, body);
        }
        instance.setIntentSource(type);
        instance.setBusinessInstanceId(businessInstanceId);
        instance.setBusinessInstance(businessInstance);
        Session session = getSession();
        Transaction tx = null;
        try{
            tx = session.beginTransaction();
            session.save(instance);
            tx.commit();
            return instance;
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            logger.error("createIntentInstance Details:" + e.getMessage());
            return null;
        } finally {
            session.close();
        }
    }

    private IntentInstance assembleIntentInstanceFormCCVPNInfo(IntentInstance instance, Object body) {
        JSONObject jsonObject = new JSONObject((Map) body);
        String intent_content = jsonObject.getString("intentContent");
        jsonObject.remove("intentContent");
        instance.setIntentConfig(jsonObject.toJSONString());
        instance.setIntentContent(intent_content);
        instance.setIntentName(jsonObject.getString("name"));
        return instance;
    }

    private IntentInstance assembleIntentInstanceFormSliceInfo(IntentInstance instance, Object body) {
        JSONObject jsonObject = new JSONObject((Map) body);
        JSONObject slicingOrderInfo = jsonObject.getJSONObject("slicing_order_info");
        String intent_content = slicingOrderInfo.getString("intentContent");
        slicingOrderInfo.remove("intentContent");
        instance.setIntentConfig(slicingOrderInfo.toJSONString());
        instance.setIntentContent(intent_content);
        instance.setIntentName(slicingOrderInfo.getString("name"));
        return instance;
    }


    @Override
    public void deleteIntent(int id) {
        Transaction tx = null;
        Session session = getSession();
        try {
            IntentInstance intentInstance = (IntentInstance)session.createQuery("from IntentInstance where id = :id")
                    .setParameter("id", id).uniqueResult();
            if (IntentConstant.MODEL_TYPE_CCVPN.equals(intentInstance.getIntentSource())) {
                deleteIntentInstance(intentInstance.getBusinessInstanceId());
            } else {
                resourceMgtService.terminateSlicingService(intentInstance.getBusinessInstanceId());
            }


            tx = session.beginTransaction();
            session.delete(intentInstance);
            tx.commit();
            logger.info("delete IntentInstance OK, id=" + intentInstance.getId());
        } catch (Exception e) {
            if(tx!=null){
                tx.rollback();
            }
            logger.error("delete IntentInstance occur exception:"+e);

        } finally {
            session.close();
        }
    }

    @Override
    public void verifyIntent(int id) {
        Session session = getSession();
        IntentInstance instance = new IntentInstance();
        try {
            String hql = "from IntentInstance where id = :id";
            Query query = session.createQuery(hql).setParameter("id", id);
            instance = (IntentInstance) query.uniqueResult();

        } catch (Exception e) {
            logger.error("verifyIntentInstance error. Details:" + e.getMessage());
        } finally {
            session.close();
        }
    }

    @Override
    public Page<IntentInstance> getIntentInstanceList(int currentPage, int pageSize) {
        Page<IntentInstance> page = new Page<IntentInstance>();
        int allRow = getIntentInstanceAllCount();
        int offset = page.countOffset(currentPage, pageSize);
        Session session = getSession();
        try{
            String hql = "from IntentInstance order by id";
            Query query = session.createQuery(hql);
            query.setFirstResult(offset);
            query.setMaxResults(pageSize);
            List<IntentInstance> list= query.list();
            page.setPageNo(currentPage);
            page.setPageSize(pageSize);
            page.setTotalRecords(allRow);
            page.setList(list);
            return page;
        } catch (Exception e) {
            logger.error("exception occurred while performing IntentInstanceServiceImpl getIntentInstanceList. Details:" + e.getMessage());
            return null;
        } finally {
            session.close();
        }
    }

    @Override
    public ServiceResult createSlicingServiceWithIntent(Object slicingOrderBody) {

        SlicingOrder slicingOrder = JSONObject.parseObject(JSONObject.toJSONString(slicingOrderBody), SlicingOrder.class);
        ServiceResult serviceResult = slicingService.createSlicingService(slicingOrder);
        ServiceCreateResult createResult = (ServiceCreateResult) serviceResult.getResult_body();
        try {
            saveSlicingServiceToAAI(createResult.getService_id(), createResult.getOperation_id(), slicingOrder);
        } catch (IOException e) {
            logger.error("save 5g slice to AAI fail!");
            throw new RuntimeException("save 5g slice to AAI fail!", e);
        }
        createIntentInstance(slicingOrderBody,createResult.getService_id(), slicingOrder.getSlicing_order_info().getName(), IntentConstant.MODEL_TYPE_5GS);
        return serviceResult;
    }

    @Override
    public int updateCCVPNInstance(CCVPNInstance instance) {
        Session session = getSession();
        Transaction tx = null;
        try{
            if (null == instance){
                logger.error("instance is null!");
                return 0;
            }
            instance.setResourceInstanceId("cll-"+instance.getInstanceId());

            CCVPNInstance ccvpnInstance = (CCVPNInstance)session.createQuery("from CCVPNInstance where instanceId = :instanceId")
                    .setParameter("instanceId", instance.getInstanceId()).uniqueResult();
            ccvpnInstance.setAccessPointOneBandWidth(instance.getAccessPointOneBandWidth());
            saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + ccvpnInstance.getInstanceId(), ccvpnInstance);

            tx = session.beginTransaction();
            session.update(ccvpnInstance);
            tx.commit();
            return 1;
        } catch (Exception e) {
            if (tx != null) {
                tx.rollback();
            }
            logger.error("Details:" + e.getMessage());
            return 0;
        } finally {
            session.close();
        }
    }

    public int getIntentInstanceAllCount() {
        Session session = getSession();
        try{
            String count="select count(*) from IntentInstance";
            Query query = session.createQuery(count);
            long q=(long)query.uniqueResult();
            return (int)q;
        } catch (Exception e) {
            logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
            return -1;
        } finally {
            session.close();
        }
    }

    public void addSubscription() throws IOException {
        Properties environment = getProperties();
        String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
        String serviceType = environment.getProperty("ccvpn.serviceType");
        Response<JSONObject> querySubscription = intentApiService.querySubscription(globalCustomerId, serviceType).execute();
        if (querySubscription.isSuccessful()) {
            return;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("service-type", serviceType);
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
        intentApiService.addSubscription(globalCustomerId, serviceType, requestBody).execute();
    }

    public Properties getProperties() throws IOException {
        String slicingPath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "ccvpn.properties";
        InputStream inputStream = new FileInputStream(new File(slicingPath));
        Properties environment = new Properties();
        environment.load(inputStream);
        return environment;
    }


    public void saveIntentInstanceToAAI(String serviceInstanceId, CCVPNInstance instance) throws IOException {
        addCustomer();
        addSubscription();
        Properties environment = getProperties();
        String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
        String serviceType = environment.getProperty("ccvpn.serviceType");
        String resourceVersion = null;
        if (serviceInstanceId != null) {
            Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
            if (queryServiceInstance.isSuccessful()) {
                JSONObject body = queryServiceInstance.body();
                resourceVersion  = body.getString("resource-version");
            }
        } else {
            serviceInstanceId = IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId();
        }
        JSONObject environmentContext = JSONObject.parseObject(JSONObject.toJSONString(instance));
        environmentContext.put("resourceInstanceId",instance.getResourceInstanceId());

        Map<String, Object> params = new HashMap<>();
        params.put("service-instance-id", serviceInstanceId);
        params.put("service-instance-name", instance.getName());
        params.put("service-type", IntentConstant.MODEL_TYPE_CCVPN);
        params.put("environment-context", environmentContext.toJSONString());
        params.put("service-instance-location-id", instance.getResourceInstanceId());
        params.put("bandwidth-total", instance.getAccessPointOneBandWidth());
        params.put("data-owner", IntentConstant.INTENT_INSTANCE_DATA_OWNER);
        if (resourceVersion != null) {
            params.put("resource-version",resourceVersion);
        }
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
        intentApiService.saveServiceInstance(globalCustomerId,serviceType,serviceInstanceId,requestBody).execute();

    }
    public void deleteIntentInstanceToAAI(String serviceInstanceId) throws IOException {
        addCustomer();
        addSubscription();
        Properties environment = getProperties();
        String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
        String serviceType = environment.getProperty("ccvpn.serviceType");
        if (serviceInstanceId == null) {
            return;
        }
        Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
        if (queryServiceInstance.isSuccessful()) {
            JSONObject body = queryServiceInstance.body();
            String resourceVersion  = body.getString("resource-version");
            intentApiService.deleteServiceInstance(globalCustomerId,serviceType,serviceInstanceId,resourceVersion).execute();
        }
    }

    @Override
    public void saveSlicingServiceToAAI(String serviceId, String operationId, SlicingOrder slicingOrder) throws IOException {
        addCustomer();
        addSubscription();
        Properties environment = getProperties();
        String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
        String serviceType = environment.getProperty("ccvpn.serviceType");
        SlicingOrderDetail slicingOrderInfo = slicingOrder.getSlicing_order_info();
        JSONObject environmentContext = JSONObject.parseObject(JSONObject.toJSONString(slicingOrderInfo));

        Map<String, Object> params = new HashMap<>();
        params.put("service-instance-id", serviceId);
        params.put("service-instance-name", slicingOrderInfo.getName());
        params.put("service-type", IntentConstant.MODEL_TYPE_5GS);
        params.put("environment-context", environmentContext.toJSONString());
        params.put("service-operation-id", operationId);
        params.put("data-rate-uplink", slicingOrderInfo.getExpDataRateUL());
        params.put("data-rate-downlink", slicingOrderInfo.getExpDataRateDL());
        params.put("latency", slicingOrderInfo.getLatency());
        params.put("max-number-of-ues", slicingOrderInfo.getMaxNumberofUEs());
        params.put("mobility", slicingOrderInfo.getUEMobilityLevel());
        params.put("resource-sharing-level", slicingOrderInfo.getResourceSharingLevel());
        params.put("data-owner", IntentConstant.INTENT_INSTANCE_DATA_OWNER);
        okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
        intentApiService.saveServiceInstance(globalCustomerId,serviceType,serviceId,requestBody).execute();
    }

}