2 * Copyright (C) 2021 CTC, Inc. and others. All rights reserved.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.onap.usecaseui.server.service.intent.impl;
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;
48 import javax.annotation.Resource;
49 import javax.transaction.Transactional;
51 import java.text.SimpleDateFormat;
53 import java.util.regex.Matcher;
54 import java.util.regex.Pattern;
56 @Service("IntentInstanceService")
58 @org.springframework.context.annotation.Configuration
59 @EnableAspectJAutoProxy
60 public class IntentInstanceServiceImpl implements IntentInstanceService {
61 private static final Logger logger = LoggerFactory.getLogger(IntentInstanceServiceImpl.class);
64 private SessionFactory sessionFactory;
66 @Resource(name = "ResourceMgtService")
67 private ResourceMgtService resourceMgtService;
69 @Resource(name = "SlicingService")
70 private SlicingService slicingService;
72 private IntentApiService intentApiService;
74 private SOService soService;
76 private final static int MAX_BANDWIDTH = 6000;
77 private final static int MIN_BANDWIDTH = 100;
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"});
82 public IntentInstanceServiceImpl() {
83 this(RestfulServices.create(IntentApiService.class),RestfulServices.create(SOService.class));
85 public IntentInstanceServiceImpl(IntentApiService intentApiService, SOService soService) {
86 this.intentApiService = intentApiService;
87 this.soService = soService;
90 private Session getSession() {
91 return sessionFactory.openSession();
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();
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+"'");
107 if(UuiCommonUtil.isNotNullOrEmpty(instance.getJobId())) {
108 String ver =instance.getJobId();
109 hql.append(" and a.job_id = '"+ver+"'");
111 if(UuiCommonUtil.isNotNullOrEmpty(instance.getStatus())) {
112 String ver =instance.getStatus();
113 hql.append(" and a.status = '"+ver+"'");
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);
127 } catch (Exception e) {
128 logger.error("exception occurred while performing AlarmsHeaderServiceImpl queryAlarmsHeader. Details:" + e.getMessage());
136 public int getAllCount(CCVPNInstance instance, int currentPage, int pageSize) {
137 Session session = getSession();
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+"'");
145 if(UuiCommonUtil.isNotNullOrEmpty(instance.getJobId())) {
146 String ver =instance.getJobId();
147 count.append(" and a.job_id = '"+ver+"'");
149 if(UuiCommonUtil.isNotNullOrEmpty(instance.getStatus())) {
150 String ver =instance.getStatus();
151 count.append(" and a.status = '"+ver+"'");
154 Query query = session.createQuery(count.toString());
155 long q=(long)query.uniqueResult();
157 } catch (Exception e) {
158 logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
166 public int createCCVPNInstance(CCVPNInstance instance) {
167 Session session = getSession();
168 Transaction tx = null;
171 if (null == instance){
172 logger.error("instance is null!");
175 String jobId = createIntentInstanceToSO(instance);
177 logger.error("create Instance error:jobId is null");
180 instance.setJobId(jobId);
181 instance.setResourceInstanceId("cll-"+instance.getInstanceId());
182 saveIntentInstanceToAAI(null, instance);
184 tx = session.beginTransaction();
185 session.save(instance);
188 } catch (Exception e) {
192 logger.error("Details:" + e.getMessage());
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", "false");
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());
226 transportNetwork.put("sla", sla);
227 transportNetwork.put("connectionLinks", connectionLinks);
228 transportNetworks.add(transportNetwork);
229 additionalProperties.put("transportNetworks", transportNetworks);
230 params.put("additionalProperties",additionalProperties);
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");
241 public void getIntentInstanceProgress() {
242 List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("0");
243 for (CCVPNInstance instance: instanceList) {
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);
253 catch (Exception e) {
254 logger.info("get progress exception:"+e);
257 saveProgress(instanceList);
261 public void getIntentInstanceCreateStatus() {
262 List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("0");
263 for (CCVPNInstance instance: instanceList) {
266 int flag = getCreateStatusByJobId(instance);
268 instance.setStatus(flag + "");
269 saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId(),instance);
272 catch (Exception e) {
273 logger.info("get progress exception:"+e);
276 saveProgress(instanceList);
280 private void saveProgress(List<CCVPNInstance> instanceList) {
281 if(instanceList == null || instanceList.isEmpty()) {
284 Session session = getSession();
285 Transaction tx = null;
287 tx = session.beginTransaction();
288 for (CCVPNInstance instance : instanceList) {
289 session.update(instance);
293 logger.info("update progress ok");
295 } catch (Exception e) {
299 logger.error("update progress exception:"+e);
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");
317 private int getCreateStatusByJobId(CCVPNInstance instance) throws IOException {
318 if (instance == null || instance.getResourceInstanceId() == null) {
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)) {
330 logger.error("getIntentInstance Create Statue Error:" + response.toString());
334 private List<CCVPNInstance> getInstanceByFinishedFlag(String flag) {
335 Session session = getSession();
337 StringBuffer sql=new StringBuffer("from CCVPNInstance where deleteState = 0 and status = '" + flag + "'");
339 Query query = session.createQuery(sql.toString());
340 List<CCVPNInstance> q=(List<CCVPNInstance>) query.list();
341 logger.debug(q.toString());
343 } catch (Exception e) {
344 logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
353 public List<CCVPNInstance> getFinishedInstanceInfo() {
354 Session session = getSession();
356 StringBuffer count=new StringBuffer("from CCVPNInstance where status = '1' and deleteState = 0");
358 Query query = session.createQuery(count.toString());
359 List<CCVPNInstance> q=(List<CCVPNInstance>) query.list();
360 logger.debug(q.toString());
362 } catch (Exception e) {
363 logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
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());
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");
396 if (networkPolicyId== null) {
397 logger.error("get network Policy Id exception. serviceInstanceId:" + instance.getResourceInstanceId());
401 Response<JSONObject> networkPolicyInfoResponse = intentApiService.getInstanceNetworkPolicyInfo(networkPolicyId).execute();
402 if (!networkPolicyInfoResponse.isSuccessful()) {
403 logger.error("get Intent-Instance networkPolicyInfo error:" + networkPolicyInfoResponse.toString());
406 JSONObject networkPolicyInfo = networkPolicyInfoResponse.body();
407 int maxBandwidth = networkPolicyInfo.getIntValue("max-bandwidth");
408 InstancePerformance instancePerformance = new InstancePerformance();
409 instancePerformance.setMaxBandwidth(maxBandwidth);
410 instancePerformance.setResourceInstanceId(instance.getResourceInstanceId());
411 instancePerformance.setJobId(instance.getJobId());
412 instancePerformance.setDate(new Date());
414 Response<JSONObject> metadatumResponse = intentApiService.getInstanceBandwidth(serviceInstanceId).execute();
415 if (!metadatumResponse.isSuccessful()) {
416 logger.error("get Intent-Instance metadatum error:" + metadatumResponse.toString());
419 JSONObject metadatum = metadatumResponse.body();
420 int metaval = metadatum.getJSONArray("metadatum").getJSONObject(0).getIntValue("metaval");
421 instancePerformance.setBandwidth(metaval);
423 Session session = getSession();
424 Transaction tx = null;
426 tx = session.beginTransaction();
427 session.save(instancePerformance);
429 } catch (Exception e) {
433 logger.error("Details:" + e.getMessage());
443 public void deleteIntentInstance(String instanceId) {
444 CCVPNInstance result = null;
445 Session session = getSession();
448 result = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
449 .setParameter("instanceId", instanceId).uniqueResult();
450 logger.info("get CCVPNInstance OK, id=" + instanceId);
452 } catch (Exception e) {
453 logger.error("getodel occur exception:"+e);
459 String serviceInstanceId = result.getResourceInstanceId();
460 deleteInstanceToSO(serviceInstanceId);
461 deleteIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-"+instanceId);
462 deleteInstance(result);
463 }catch (Exception e) {
464 logger.error("delete instance to SO error :" + e);
469 private void deleteInstanceToSO(String serviceInstanceId) throws IOException {
470 JSONObject params = new JSONObject();
471 params.put("serviceInstanceID", serviceInstanceId);
472 params.put("globalSubscriberId", "IBNCustomer");
473 params.put("subscriptionServiceType", "IBN");
474 params.put("serviceType", "CLL");
475 JSONObject additionalProperties = new JSONObject();
476 additionalProperties.put("enableSdnc", "false");
477 params.put("additionalProperties", additionalProperties);
478 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
479 intentApiService.deleteIntentInstance(requestBody).execute();
481 private String deleteInstance(CCVPNInstance instance) {
482 Transaction tx = null;
484 Session session = getSession();
486 tx = session.beginTransaction();
488 session.delete(instance);
490 logger.info("delete instance OK, id=" + instance.getInstanceId());
493 } catch (Exception e) {
497 logger.error("delete instance occur exception:"+e);
506 public void activeIntentInstance(String instanceId) {
507 CCVPNInstance instance = null;
508 Session session = getSession();
509 Transaction tx = null;
512 instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId and status = :status")
513 .setParameter("instanceId", instanceId).setParameter("status", "3").uniqueResult();
514 logger.info("get instance OK, id=" + instanceId);
516 if (null == instance) {
517 logger.error("instance is null!");
521 String jobId = createIntentInstanceToSO(instance);
522 instance.setStatus("0");
523 instance.setJobId(jobId);
524 tx = session.beginTransaction();
525 session.save(instance);
528 }catch (Exception e) {
532 logger.error("active instance to SO error :" + e);
538 public void invalidIntentInstance(String instanceId) {
539 CCVPNInstance instance = null;
540 Session session = getSession();
541 Transaction tx = null;
543 instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
544 .setParameter("instanceId", instanceId).uniqueResult();
545 logger.info("get instance OK, id=" + instanceId);
547 if (null == instance) {
548 logger.error("instance is null!");
551 deleteInstanceToSO(instance.getInstanceId());
552 instance.setStatus("3");
553 tx = session.beginTransaction();
554 session.save(instance);
558 }catch (Exception e) {
562 logger.error("invalid instance to SO error :" + e);
569 public Map<String, Object> queryInstancePerformanceData(String instanceId) {
570 Session session = getSession();
572 String hql = "from CCVPNInstance i, InstancePerformance p where i.resourceInstanceId = p.resourceInstanceId and i.instanceId = :instanceId and i.deleteState = 0 order by p.date";
573 Query query = session.createQuery(hql).setParameter("instanceId", instanceId);
574 List<Object[]> queryResult= query.list();
575 List<String> date = new ArrayList<>();
576 List<Integer> bandwidth = new ArrayList<>();
577 List<Integer> maxBandwidth = new ArrayList<>();
578 SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
579 for (int i = queryResult.size() > 50? queryResult.size() - 50 : 0; i < queryResult.size(); i++) {
580 Object[] o = queryResult.get(i);
581 InstancePerformance performance = (InstancePerformance) o[1];
582 date.add(ft.format(performance.getDate()));
583 bandwidth.add(performance.getBandwidth());
584 maxBandwidth.add(performance.getMaxBandwidth());
586 Map<String, Object> xAxis = new HashMap<>();
587 xAxis.put("data",date);
588 Map<String, Object> bandwidthData = new HashMap<>();
589 bandwidthData.put("data",bandwidth);
590 Map<String, Object> maxBandwidthData = new HashMap<>();
591 maxBandwidthData.put("data",maxBandwidth);
592 List<Map<String, Object>> series = new ArrayList<>();
593 series.add(bandwidthData);
594 series.add(maxBandwidthData);
596 Map<String, Object> result = new HashMap<>();
597 result.put("xAxis", xAxis);
598 result.put("series", series);
601 }catch (Exception e) {
602 logger.error("invalid instance to SO error :" + e);
610 public Object queryAccessNodeInfo() throws IOException {
611 Map<String, Object> result = new HashMap<>();
612 List<String> accessNodeList = new ArrayList<>();
613 List<String> cloudAccessNodeList = new ArrayList<>();
614 Response<JSONObject> response = intentApiService.queryNetworkRoute().execute();
615 if (!response.isSuccessful()) {
616 logger.error(response.toString());
617 throw new RuntimeException("Query Access Node Info Error");
619 JSONObject body = response.body();
620 JSONArray data = body.getJSONArray("network-route");
621 for (int i = 0; i<data.size(); i++) {
622 JSONObject nodeInfo = data.getJSONObject(i);
623 if ("ROOT".equals(nodeInfo.getString("type"))) {
624 cloudAccessNodeList.add(nodeInfo.getString("route-id"));
627 accessNodeList.add(nodeInfo.getString("route-id"));
630 result.put("accessNodeList",accessNodeList);
631 result.put("cloudAccessNodeList",cloudAccessNodeList);
636 public JSONObject getInstanceStatus(JSONArray ids) {
637 Session session = getSession();
639 JSONObject result = new JSONObject();
640 JSONArray instanceInfos = new JSONArray();
641 String hql = "from CCVPNInstance i where i.instanceId in (:ids)";
642 Query query = session.createQuery(hql).setParameter("ids", ids);
643 List<CCVPNInstance> queryResult= query.list();
644 if (queryResult != null && queryResult.size() > 0) {
645 for (CCVPNInstance instance : queryResult) {
646 JSONObject instanceInfo = new JSONObject();
647 instanceInfo.put("id", instance.getInstanceId());
648 instanceInfo.put("status", instance.getStatus());
649 instanceInfos.add(instanceInfo);
652 result.put("IntentInstances",instanceInfos);
655 } catch (Exception e) {
656 logger.error("get Instance status error : " + e.getMessage());
664 public String formatBandwidth(String strValue) {
666 Pattern pattern = Pattern.compile("(\\d+)([\\w ]*)");
667 Matcher matcher = pattern.matcher(strValue);
671 if (matcher.matches()) {
672 dataRate = Integer.parseInt(matcher.group(1));
673 String company = matcher.group(2).trim().toLowerCase();
674 if (GB_COMPANY.contains(company)) {
675 dataRate = dataRate * 1000;
677 else if (!MB_COMPANY.contains(company)) {
680 dataRate = dataRate < MIN_BANDWIDTH ? MIN_BANDWIDTH : (dataRate > MAX_BANDWIDTH ? MAX_BANDWIDTH : dataRate);
687 public String formatCloudPoint(String cloudPoint) {
688 String cloudPointAlias = "";
689 switch (cloudPoint) {
691 cloudPointAlias = "tranportEp_dst_ID_212_1";
694 return cloudPointAlias;
697 public String formatAccessPoint(String accessPoint) {
698 String accessPointAlias = "";
699 switch (accessPoint) {
701 accessPointAlias = "tranportEp_src_ID_111_1";
704 accessPointAlias = "tranportEp_src_ID_111_2";
706 case "Access three" :
707 accessPointAlias = "tranportEp_src_ID_113_1";
710 return accessPointAlias;
713 public void addCustomer() throws IOException {
714 Properties environment = getProperties();
715 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
716 Response<JSONObject> queryCustomerResponse = intentApiService.queryCustomer(globalCustomerId).execute();
717 if (queryCustomerResponse.isSuccessful()) {
720 String subscriberName = environment.getProperty("ccvpn.subscriberName");
721 String subscriberType = environment.getProperty("ccvpn.subscriberType");
722 Map<String, Object> params = new HashMap<>();
723 params.put("global-customer-id", globalCustomerId);
724 params.put("subscriber-name", subscriberName);
725 params.put("subscriber-type", subscriberType);
726 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
727 intentApiService.addCustomer(globalCustomerId, requestBody).execute();
731 public IntentInstance createIntentInstance(Object body,String businessInstanceId, String businessInstance, String type) {
732 IntentInstance instance = new IntentInstance();
733 if (IntentConstant.MODEL_TYPE_CCVPN.equals(type)) {
734 assembleIntentInstanceFormCCVPNInfo(instance, body);
736 else if (IntentConstant.MODEL_TYPE_5GS.equals(type)) {
737 assembleIntentInstanceFormSliceInfo(instance, body);
739 instance.setIntentSource(type);
740 instance.setBusinessInstanceId(businessInstanceId);
741 instance.setBusinessInstance(businessInstance);
742 Session session = getSession();
743 Transaction tx = null;
745 tx = session.beginTransaction();
746 session.save(instance);
749 } catch (Exception e) {
753 logger.error("createIntentInstance Details:" + e.getMessage());
760 private IntentInstance assembleIntentInstanceFormCCVPNInfo(IntentInstance instance, Object body) {
761 JSONObject jsonObject = new JSONObject((Map) body);
762 String intent_content = jsonObject.getString("intentContent");
763 jsonObject.remove("intentContent");
764 instance.setIntentConfig(jsonObject.toJSONString());
765 instance.setIntentContent(intent_content);
766 instance.setIntentName(jsonObject.getString("name"));
770 private IntentInstance assembleIntentInstanceFormSliceInfo(IntentInstance instance, Object body) {
771 JSONObject jsonObject = new JSONObject((Map) body);
772 JSONObject slicingOrderInfo = jsonObject.getJSONObject("slicing_order_info");
773 String intent_content = slicingOrderInfo.getString("intentContent");
774 slicingOrderInfo.remove("intentContent");
775 instance.setIntentConfig(slicingOrderInfo.toJSONString());
776 instance.setIntentContent(intent_content);
777 instance.setIntentName(slicingOrderInfo.getString("name"));
783 public void deleteIntent(int id) {
784 Transaction tx = null;
785 Session session = getSession();
787 IntentInstance intentInstance = (IntentInstance)session.createQuery("from IntentInstance where id = :id")
788 .setParameter("id", id).uniqueResult();
789 if (IntentConstant.MODEL_TYPE_CCVPN.equals(intentInstance.getIntentSource())) {
790 deleteIntentInstance(intentInstance.getBusinessInstanceId());
792 resourceMgtService.terminateSlicingService(intentInstance.getBusinessInstanceId());
796 tx = session.beginTransaction();
797 session.delete(intentInstance);
799 logger.info("delete IntentInstance OK, id=" + intentInstance.getId());
800 } catch (Exception e) {
804 logger.error("delete IntentInstance occur exception:"+e);
812 public void verifyIntent(int id) {
813 Session session = getSession();
814 IntentInstance instance = new IntentInstance();
816 String hql = "from IntentInstance where id = :id";
817 Query query = session.createQuery(hql).setParameter("id", id);
818 instance = (IntentInstance) query.uniqueResult();
820 } catch (Exception e) {
821 logger.error("verifyIntentInstance error. Details:" + e.getMessage());
828 public Page<IntentInstance> getIntentInstanceList(int currentPage, int pageSize) {
829 Page<IntentInstance> page = new Page<IntentInstance>();
830 int allRow = getIntentInstanceAllCount();
831 int offset = page.countOffset(currentPage, pageSize);
832 Session session = getSession();
834 String hql = "from IntentInstance order by id";
835 Query query = session.createQuery(hql);
836 query.setFirstResult(offset);
837 query.setMaxResults(pageSize);
838 List<IntentInstance> list= query.list();
839 page.setPageNo(currentPage);
840 page.setPageSize(pageSize);
841 page.setTotalRecords(allRow);
844 } catch (Exception e) {
845 logger.error("exception occurred while performing IntentInstanceServiceImpl getIntentInstanceList. Details:" + e.getMessage());
853 public ServiceResult createSlicingServiceWithIntent(Object slicingOrderBody) {
855 SlicingOrder slicingOrder = JSONObject.parseObject(JSONObject.toJSONString(slicingOrderBody), SlicingOrder.class);
856 ServiceResult serviceResult = slicingService.createSlicingService(slicingOrder);
857 ServiceCreateResult createResult = (ServiceCreateResult) serviceResult.getResult_body();
859 createIntentInstance(slicingOrderBody,createResult.getService_id(), slicingOrder.getSlicing_order_info().getName(), IntentConstant.MODEL_TYPE_5GS);
860 return serviceResult;
864 public int updateCCVPNInstance(CCVPNInstance instance) {
865 Session session = getSession();
866 Transaction tx = null;
868 if (null == instance){
869 logger.error("instance is null!");
872 instance.setResourceInstanceId("cll-"+instance.getInstanceId());
874 CCVPNInstance ccvpnInstance = (CCVPNInstance)session.createQuery("from CCVPNInstance where instanceId = :instanceId")
875 .setParameter("instanceId", instance.getInstanceId()).uniqueResult();
876 ccvpnInstance.setAccessPointOneBandWidth(instance.getAccessPointOneBandWidth());
877 saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + ccvpnInstance.getInstanceId(), ccvpnInstance);
879 tx = session.beginTransaction();
880 session.update(ccvpnInstance);
883 } catch (Exception e) {
887 logger.error("Details:" + e.getMessage());
894 public int getIntentInstanceAllCount() {
895 Session session = getSession();
897 String count="select count(*) from IntentInstance";
898 Query query = session.createQuery(count);
899 long q=(long)query.uniqueResult();
901 } catch (Exception e) {
902 logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
909 public void addSubscription() throws IOException {
910 Properties environment = getProperties();
911 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
912 String serviceType = environment.getProperty("ccvpn.serviceType");
913 Response<JSONObject> querySubscription = intentApiService.querySubscription(globalCustomerId, serviceType).execute();
914 if (querySubscription.isSuccessful()) {
917 Map<String, Object> params = new HashMap<>();
918 params.put("service-type", serviceType);
919 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
920 intentApiService.addSubscription(globalCustomerId, serviceType, requestBody).execute();
923 public Properties getProperties() throws IOException {
924 String slicingPath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "ccvpn.properties";
925 InputStream inputStream = new FileInputStream(new File(slicingPath));
926 Properties environment = new Properties();
927 environment.load(inputStream);
932 public void saveIntentInstanceToAAI(String serviceInstanceId, CCVPNInstance instance) throws IOException {
935 Properties environment = getProperties();
936 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
937 String serviceType = environment.getProperty("ccvpn.serviceType");
938 String resourceVersion = null;
939 if (serviceInstanceId != null) {
940 Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
941 if (queryServiceInstance.isSuccessful()) {
942 JSONObject body = queryServiceInstance.body();
943 resourceVersion = body.getString("resource-version");
946 serviceInstanceId = IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId();
948 JSONObject environmentContext = JSONObject.parseObject(JSONObject.toJSONString(instance));
949 environmentContext.put("resourceInstanceId",instance.getResourceInstanceId());
951 Map<String, Object> params = new HashMap<>();
952 params.put("service-instance-id", serviceInstanceId);
953 params.put("service-instance-name", instance.getName());
954 params.put("service-type", IntentConstant.MODEL_TYPE_CCVPN);
955 params.put("environment-context", environmentContext.toJSONString());
956 params.put("service-instance-location-id", instance.getResourceInstanceId());
957 params.put("bandwidth-total", instance.getAccessPointOneBandWidth());
958 params.put("data-owner", IntentConstant.INTENT_INSTANCE_DATA_OWNER);
959 if (resourceVersion != null) {
960 params.put("resource-version",resourceVersion);
962 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
963 intentApiService.saveServiceInstance(globalCustomerId,serviceType,serviceInstanceId,requestBody).execute();
966 public void deleteIntentInstanceToAAI(String serviceInstanceId) throws IOException {
969 Properties environment = getProperties();
970 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
971 String serviceType = environment.getProperty("ccvpn.serviceType");
972 if (serviceInstanceId == null) {
975 Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
976 if (queryServiceInstance.isSuccessful()) {
977 JSONObject body = queryServiceInstance.body();
978 String resourceVersion = body.getString("resource-version");
979 intentApiService.deleteServiceInstance(globalCustomerId,serviceType,serviceInstanceId,resourceVersion).execute();