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.csmf.SlicingOrderDetail;
28 import org.onap.usecaseui.server.bean.intent.InstancePerformance;
29 import org.onap.usecaseui.server.bean.intent.CCVPNInstance;
30 import org.onap.usecaseui.server.bean.intent.IntentInstance;
31 import org.onap.usecaseui.server.bean.nsmf.common.ServiceResult;
32 import org.onap.usecaseui.server.constant.IntentConstant;
33 import org.onap.usecaseui.server.service.csmf.SlicingService;
34 import org.onap.usecaseui.server.service.intent.IntentApiService;
35 import org.onap.usecaseui.server.service.intent.IntentInstanceService;
36 import org.onap.usecaseui.server.service.lcm.domain.so.SOService;
37 import org.onap.usecaseui.server.service.nsmf.ResourceMgtService;
38 import org.onap.usecaseui.server.util.Page;
39 import org.onap.usecaseui.server.util.RestfulServices;
40 import org.onap.usecaseui.server.util.UuiCommonUtil;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.context.annotation.EnableAspectJAutoProxy;
45 import org.springframework.stereotype.Service;
46 import retrofit2.Call;
47 import retrofit2.Response;
49 import javax.annotation.Resource;
50 import javax.transaction.Transactional;
52 import java.text.SimpleDateFormat;
54 import java.util.regex.Matcher;
55 import java.util.regex.Pattern;
57 @Service("IntentInstanceService")
59 @org.springframework.context.annotation.Configuration
60 @EnableAspectJAutoProxy
61 public class IntentInstanceServiceImpl implements IntentInstanceService {
62 private static final Logger logger = LoggerFactory.getLogger(IntentInstanceServiceImpl.class);
65 private SessionFactory sessionFactory;
67 @Resource(name = "ResourceMgtService")
68 private ResourceMgtService resourceMgtService;
70 @Resource(name = "SlicingService")
71 private SlicingService slicingService;
73 private IntentApiService intentApiService;
75 private SOService soService;
77 private final static int MAX_BANDWIDTH = 6000;
78 private final static int MIN_BANDWIDTH = 100;
80 private final static List<String> GB_COMPANY = Arrays.asList(new String[] {"gbps", "gb"});
81 private final static List<String> MB_COMPANY = Arrays.asList(new String[] {"mbps", "mb"});
83 public IntentInstanceServiceImpl() {
84 this(RestfulServices.create(IntentApiService.class),RestfulServices.create(SOService.class));
86 public IntentInstanceServiceImpl(IntentApiService intentApiService, SOService soService) {
87 this.intentApiService = intentApiService;
88 this.soService = soService;
91 private Session getSession() {
92 return sessionFactory.openSession();
96 public Page<CCVPNInstance> queryIntentInstance(CCVPNInstance instance, int currentPage, int pageSize) {
97 Page<CCVPNInstance> page = new Page<CCVPNInstance>();
98 int allRow =this.getAllCount(instance,currentPage,pageSize);
99 int offset = page.countOffset(currentPage, pageSize);
100 Session session = getSession();
102 StringBuffer hql =new StringBuffer("from CCVPNInstance a where deleteState = 0");
103 if (null != instance) {
104 if(UuiCommonUtil.isNotNullOrEmpty(instance.getInstanceId())) {
105 String ver =instance.getInstanceId();
106 hql.append(" and a.instance_id = '"+ver+"'");
108 if(UuiCommonUtil.isNotNullOrEmpty(instance.getJobId())) {
109 String ver =instance.getJobId();
110 hql.append(" and a.job_id = '"+ver+"'");
112 if(UuiCommonUtil.isNotNullOrEmpty(instance.getStatus())) {
113 String ver =instance.getStatus();
114 hql.append(" and a.status = '"+ver+"'");
117 hql.append(" order by id");
118 logger.info("AlarmsHeaderServiceImpl queryIntentInstance: instance={}", instance);
119 Query query = session.createQuery(hql.toString());
120 query.setFirstResult(offset);
121 query.setMaxResults(pageSize);
122 List<CCVPNInstance> list= query.list();
123 page.setPageNo(currentPage);
124 page.setPageSize(pageSize);
125 page.setTotalRecords(allRow);
128 } catch (Exception e) {
129 logger.error("exception occurred while performing AlarmsHeaderServiceImpl queryAlarmsHeader. Details:" + e.getMessage());
137 public int getAllCount(CCVPNInstance instance, int currentPage, int pageSize) {
138 Session session = getSession();
140 StringBuffer count=new StringBuffer("select count(*) from CCVPNInstance a where deleteState = 0");
141 if (null != instance) {
142 if(UuiCommonUtil.isNotNullOrEmpty(instance.getInstanceId())) {
143 String ver =instance.getInstanceId();
144 count.append(" and a.instance_id = '"+ver+"'");
146 if(UuiCommonUtil.isNotNullOrEmpty(instance.getJobId())) {
147 String ver =instance.getJobId();
148 count.append(" and a.job_id = '"+ver+"'");
150 if(UuiCommonUtil.isNotNullOrEmpty(instance.getStatus())) {
151 String ver =instance.getStatus();
152 count.append(" and a.status = '"+ver+"'");
155 Query query = session.createQuery(count.toString());
156 long q=(long)query.uniqueResult();
158 } catch (Exception e) {
159 logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
167 public int createCCVPNInstance(CCVPNInstance instance) {
168 Session session = getSession();
169 Transaction tx = null;
172 if (null == instance){
173 logger.error("instance is null!");
176 String jobId = createIntentInstanceToSO(instance);
178 logger.error("create Instance error:jobId is null");
181 instance.setJobId(jobId);
182 instance.setResourceInstanceId("cll-"+instance.getInstanceId());
183 saveIntentInstanceToAAI(null, instance);
185 tx = session.beginTransaction();
186 session.save(instance);
189 } catch (Exception e) {
193 logger.error("Details:" + e.getMessage());
200 public String createIntentInstanceToSO(CCVPNInstance instance) throws IOException {
201 Map<String, Object> params = new HashMap<>();
202 params.put("name", instance.getName());
203 params.put("modelInvariantUuid", "6790ab0e-034f-11eb-adc1-0242ac120002");
204 params.put("modelUuid", "6790ab0e-034f-11eb-adc1-0242ac120002");
205 params.put("globalSubscriberId", "IBNCustomer");
206 params.put("subscriptionServiceType", "IBN");
207 params.put("serviceType", "CLL");
208 Map<String, Object> additionalProperties = new HashMap<>();
209 additionalProperties.put("enableSdnc", "true");
210 additionalProperties.put("serviceInstanceID", "cll-" + instance.getInstanceId());
211 List<Map<String, Object>> transportNetworks = new ArrayList<>();
212 Map<String, Object> transportNetwork = new HashMap<>();
213 transportNetwork.put("id", "");
214 Map<String, Object> sla = new HashMap<>();
215 sla.put("latency", "2");
216 sla.put("maxBandwidth", instance.getAccessPointOneBandWidth());
217 List<Map<String, Object>> connectionLinks = new ArrayList<>();
218 Map<String, Object> connectionLink = new HashMap<>();
219 connectionLink.put("name", "");
220 connectionLink.put("transportEndpointA", instance.getAccessPointOneName());
221 connectionLink.put("transportEndpointB", instance.getCloudPointName());
222 connectionLinks.add(connectionLink);
223 if (instance.getProtectStatus() == 1) {
224 sla.put("protectionType", instance.getProtectionType());
225 connectionLink.put("transportEndpointBProtection", instance.getProtectionCloudPointName());
227 transportNetwork.put("sla", sla);
228 transportNetwork.put("connectionLinks", connectionLinks);
229 transportNetworks.add(transportNetwork);
230 additionalProperties.put("transportNetworks", transportNetworks);
231 params.put("additionalProperties",additionalProperties);
233 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
234 Response<JSONObject> response = intentApiService.createIntentInstance(requestBody).execute();
235 if (response.isSuccessful()) {
236 return response.body().getString("jobId");
242 public void getIntentInstanceProgress() {
243 List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("0");
244 for (CCVPNInstance instance: instanceList) {
247 int progress = getProgressByJobId(instance);
248 instance.setProgress(progress);
249 if (progress >=100) {
250 instance.setStatus("1");
251 saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId(),instance);
254 catch (Exception e) {
255 logger.info("get progress exception:"+e);
258 saveProgress(instanceList);
262 public void getIntentInstanceCreateStatus() {
263 List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("0");
264 for (CCVPNInstance instance: instanceList) {
267 int flag = getCreateStatusByJobId(instance);
269 instance.setStatus(flag + "");
270 saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId(),instance);
273 catch (Exception e) {
274 logger.info("get progress exception:"+e);
277 saveProgress(instanceList);
281 private void saveProgress(List<CCVPNInstance> instanceList) {
282 if(instanceList == null || instanceList.isEmpty()) {
285 Session session = getSession();
286 Transaction tx = null;
288 tx = session.beginTransaction();
289 for (CCVPNInstance instance : instanceList) {
290 session.update(instance);
294 logger.info("update progress ok");
296 } catch (Exception e) {
300 logger.error("update progress exception:"+e);
307 private int getProgressByJobId(CCVPNInstance instance) throws IOException {
308 Response<JSONObject> response = intentApiService.queryOperationProgress(instance.getResourceInstanceId(), instance.getJobId()).execute();
309 logger.debug(response.toString());
310 if (response.isSuccessful()) {
311 if (response.body().containsKey("operation")) {
312 return response.body().getJSONObject("operation").getInteger("progress");
318 private int getCreateStatusByJobId(CCVPNInstance instance) throws IOException {
319 if (instance == null || instance.getResourceInstanceId() == null) {
322 Response<JSONObject> response = intentApiService.getInstanceInfo(instance.getResourceInstanceId()).execute();
323 logger.debug(response.toString());
324 if (response.isSuccessful()) {
325 String status = response.body().getString("orchestration-status");
326 if ("created".equals(status)) {
331 logger.error("getIntentInstance Create Statue Error:" + response.toString());
335 private List<CCVPNInstance> getInstanceByFinishedFlag(String flag) {
336 Session session = getSession();
338 StringBuffer sql=new StringBuffer("from CCVPNInstance where deleteState = 0 and status = '" + flag + "'");
340 Query query = session.createQuery(sql.toString());
341 List<CCVPNInstance> q=(List<CCVPNInstance>) query.list();
342 logger.debug(q.toString());
344 } catch (Exception e) {
345 logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
354 public List<CCVPNInstance> getFinishedInstanceInfo() {
355 Session session = getSession();
357 StringBuffer count=new StringBuffer("from CCVPNInstance where status = '1' and deleteState = 0");
359 Query query = session.createQuery(count.toString());
360 List<CCVPNInstance> q=(List<CCVPNInstance>) query.list();
361 logger.debug(q.toString());
363 } catch (Exception e) {
364 logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
372 public void getIntentInstanceBandwidth() throws IOException {
373 List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("1");
374 for (CCVPNInstance instance : instanceList) {
375 String serviceInstanceId = instance.getResourceInstanceId();
376 Response<JSONObject> response = intentApiService.getInstanceNetworkInfo(serviceInstanceId).execute();
377 if (!response.isSuccessful()) {
378 logger.error("get Intent-Instance Bandwidth error:" + response.toString());
381 JSONObject responseBody = response.body();
382 JSONObject allottedResource = responseBody.getJSONObject("allotted-resources").getJSONArray("allotted-resource").getJSONObject(0);
383 JSONArray relationshipList = allottedResource.getJSONObject("relationship-list").getJSONArray("relationship");
384 String networkPolicyId = null;
385 for (int i = 0; i<relationshipList.size();i++) {
386 if ("network-policy".equals(relationshipList.getJSONObject(i).getString("related-to"))) {
387 JSONArray datas = relationshipList.getJSONObject(i).getJSONArray("relationship-data");
388 for (int j = 0; j<relationshipList.size();j++) {
389 if ("network-policy.network-policy-id".equals(datas.getJSONObject(j).getString("relationship-key"))) {
390 networkPolicyId = datas.getJSONObject(j).getString("relationship-value");
397 if (networkPolicyId== null) {
398 logger.error("get network Policy Id exception. serviceInstanceId:" + instance.getResourceInstanceId());
402 Response<JSONObject> networkPolicyInfoResponse = intentApiService.getInstanceNetworkPolicyInfo(networkPolicyId).execute();
403 if (!networkPolicyInfoResponse.isSuccessful()) {
404 logger.error("get Intent-Instance networkPolicyInfo error:" + networkPolicyInfoResponse.toString());
407 JSONObject networkPolicyInfo = networkPolicyInfoResponse.body();
408 int maxBandwidth = networkPolicyInfo.getIntValue("max-bandwidth") * 1000;
409 InstancePerformance instancePerformance = new InstancePerformance();
410 instancePerformance.setMaxBandwidth(maxBandwidth);
411 instancePerformance.setResourceInstanceId(instance.getResourceInstanceId());
412 instancePerformance.setJobId(instance.getJobId());
413 instancePerformance.setDate(new Date());
415 Response<JSONObject> metadatumResponse = intentApiService.getInstanceBandwidth(serviceInstanceId).execute();
416 if (!metadatumResponse.isSuccessful()) {
417 logger.error("get Intent-Instance metadatum error:" + metadatumResponse.toString());
420 logger.debug("get Intent-Instance metadatum ok: instance id:" + instance.getInstanceId() + ", metadatum info:" + metadatumResponse.toString());
422 JSONObject metadatum = metadatumResponse.body();
423 JSONArray metadatumArr = metadatum.getJSONArray("metadatum");
425 for (int i = 0; i < metadatumArr.size(); i++) {
426 if (metaval == -1 || metaval > metadatumArr.getJSONObject(i).getIntValue("metaval")) {
427 metaval = metadatumArr.getJSONObject(i).getIntValue("metaval");
430 instancePerformance.setBandwidth(metaval);
432 Session session = getSession();
433 Transaction tx = null;
435 tx = session.beginTransaction();
436 session.save(instancePerformance);
438 } catch (Exception e) {
442 logger.error("Details:" + e.getMessage());
452 public void deleteIntentInstance(String instanceId) {
453 CCVPNInstance result = null;
454 Session session = getSession();
457 result = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
458 .setParameter("instanceId", instanceId).uniqueResult();
459 logger.info("get CCVPNInstance OK, id=" + instanceId);
461 } catch (Exception e) {
462 logger.error("getodel occur exception:"+e);
468 String serviceInstanceId = result.getResourceInstanceId();
469 deleteInstanceToSO(serviceInstanceId);
470 deleteIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-"+instanceId);
471 deleteInstance(result);
472 }catch (Exception e) {
473 logger.error("delete instance to SO error :" + e);
478 private void deleteInstanceToSO(String serviceInstanceId) throws IOException {
479 JSONObject params = new JSONObject();
480 params.put("serviceInstanceID", serviceInstanceId);
481 params.put("globalSubscriberId", "IBNCustomer");
482 params.put("subscriptionServiceType", "IBN");
483 params.put("serviceType", "CLL");
484 JSONObject additionalProperties = new JSONObject();
485 additionalProperties.put("enableSdnc", "true");
486 params.put("additionalProperties", additionalProperties);
487 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
488 intentApiService.deleteIntentInstance(requestBody).execute();
490 private String deleteInstance(CCVPNInstance instance) {
491 Transaction tx = null;
493 Session session = getSession();
495 tx = session.beginTransaction();
497 session.delete(instance);
499 logger.info("delete instance OK, id=" + instance.getInstanceId());
502 } catch (Exception e) {
506 logger.error("delete instance occur exception:"+e);
515 public void activeIntentInstance(String instanceId) {
516 CCVPNInstance instance = null;
517 Session session = getSession();
518 Transaction tx = null;
521 instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId and status = :status")
522 .setParameter("instanceId", instanceId).setParameter("status", "3").uniqueResult();
523 logger.info("get instance OK, id=" + instanceId);
525 if (null == instance) {
526 logger.error("instance is null!");
530 String jobId = createIntentInstanceToSO(instance);
531 instance.setStatus("0");
532 instance.setJobId(jobId);
533 tx = session.beginTransaction();
534 session.save(instance);
537 }catch (Exception e) {
541 logger.error("active instance to SO error :" + e);
547 public void invalidIntentInstance(String instanceId) {
548 CCVPNInstance instance = null;
549 Session session = getSession();
550 Transaction tx = null;
552 instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
553 .setParameter("instanceId", instanceId).uniqueResult();
554 logger.info("get instance OK, id=" + instanceId);
556 if (null == instance) {
557 logger.error("instance is null!");
560 deleteInstanceToSO(instance.getInstanceId());
561 instance.setStatus("3");
562 tx = session.beginTransaction();
563 session.save(instance);
567 }catch (Exception e) {
571 logger.error("invalid instance to SO error :" + e);
578 public Map<String, Object> queryInstancePerformanceData(String instanceId) {
579 Session session = getSession();
581 String hql = "from CCVPNInstance i, InstancePerformance p where i.resourceInstanceId = p.resourceInstanceId and i.instanceId = :instanceId and i.deleteState = 0 order by p.date";
582 Query query = session.createQuery(hql).setParameter("instanceId", instanceId);
583 List<Object[]> queryResult= query.list();
584 List<String> date = new ArrayList<>();
585 List<Integer> bandwidth = new ArrayList<>();
586 List<Integer> maxBandwidth = new ArrayList<>();
587 SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
588 for (int i = queryResult.size() > 50? queryResult.size() - 50 : 0; i < queryResult.size(); i++) {
589 Object[] o = queryResult.get(i);
590 InstancePerformance performance = (InstancePerformance) o[1];
591 date.add(ft.format(performance.getDate()));
592 bandwidth.add(performance.getBandwidth());
593 maxBandwidth.add(performance.getMaxBandwidth());
595 Map<String, Object> xAxis = new HashMap<>();
596 xAxis.put("data",date);
597 Map<String, Object> bandwidthData = new HashMap<>();
598 bandwidthData.put("data",bandwidth);
599 Map<String, Object> maxBandwidthData = new HashMap<>();
600 maxBandwidthData.put("data",maxBandwidth);
601 List<Map<String, Object>> series = new ArrayList<>();
602 series.add(bandwidthData);
603 series.add(maxBandwidthData);
605 Map<String, Object> result = new HashMap<>();
606 result.put("xAxis", xAxis);
607 result.put("series", series);
610 }catch (Exception e) {
611 logger.error("invalid instance to SO error :" + e);
619 public Object queryAccessNodeInfo() throws IOException {
620 Map<String, Object> result = new HashMap<>();
621 List<String> accessNodeList = new ArrayList<>();
622 List<String> cloudAccessNodeList = new ArrayList<>();
623 Response<JSONObject> response = intentApiService.queryNetworkRoute().execute();
624 if (!response.isSuccessful()) {
625 logger.error(response.toString());
626 throw new RuntimeException("Query Access Node Info Error");
628 JSONObject body = response.body();
629 JSONArray data = body.getJSONArray("network-route");
630 for (int i = 0; i<data.size(); i++) {
631 JSONObject nodeInfo = data.getJSONObject(i);
632 if ("ROOT".equals(nodeInfo.getString("type"))) {
633 cloudAccessNodeList.add(nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
636 accessNodeList.add(nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
638 IntentConstant.NetWorkNodeAlias.put(nodeInfo.getString("route-id"), nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
640 result.put("accessNodeList",accessNodeList);
641 result.put("cloudAccessNodeList",cloudAccessNodeList);
646 public JSONObject getInstanceStatus(JSONArray ids) {
647 Session session = getSession();
649 JSONObject result = new JSONObject();
650 JSONArray instanceInfos = new JSONArray();
651 String hql = "from CCVPNInstance i where i.instanceId in (:ids)";
652 Query query = session.createQuery(hql).setParameter("ids", ids);
653 List<CCVPNInstance> queryResult= query.list();
654 if (queryResult != null && queryResult.size() > 0) {
655 for (CCVPNInstance instance : queryResult) {
656 JSONObject instanceInfo = new JSONObject();
657 instanceInfo.put("id", instance.getInstanceId());
658 instanceInfo.put("status", instance.getStatus());
659 instanceInfos.add(instanceInfo);
662 result.put("IntentInstances",instanceInfos);
665 } catch (Exception e) {
666 logger.error("get Instance status error : " + e.getMessage());
674 public String formatBandwidth(String strValue) {
676 Pattern pattern = Pattern.compile("(\\d+)([\\w ]*)");
677 Matcher matcher = pattern.matcher(strValue);
681 if (matcher.matches()) {
682 dataRate = Integer.parseInt(matcher.group(1));
683 String company = matcher.group(2).trim().toLowerCase();
684 if (GB_COMPANY.contains(company)) {
685 dataRate = dataRate * 1000;
687 else if (!MB_COMPANY.contains(company)) {
690 dataRate = dataRate < MIN_BANDWIDTH ? MIN_BANDWIDTH : (dataRate > MAX_BANDWIDTH ? MAX_BANDWIDTH : dataRate);
697 public String formatCloudPoint(String cloudPoint) {
698 String cloudPointAlias = "";
699 switch (cloudPoint) {
701 cloudPointAlias = "tranportEp_dst_ID_212_1";
704 return cloudPointAlias;
707 public String formatAccessPoint(String accessPoint) {
708 String accessPointAlias = "";
709 switch (accessPoint) {
711 accessPointAlias = "tranportEp_src_ID_111_1";
714 accessPointAlias = "tranportEp_src_ID_111_2";
716 case "Access three" :
717 accessPointAlias = "tranportEp_src_ID_113_1";
720 return accessPointAlias;
723 public void addCustomer() throws IOException {
724 Properties environment = getProperties();
725 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
726 Response<JSONObject> queryCustomerResponse = intentApiService.queryCustomer(globalCustomerId).execute();
727 if (queryCustomerResponse.isSuccessful()) {
730 String subscriberName = environment.getProperty("ccvpn.subscriberName");
731 String subscriberType = environment.getProperty("ccvpn.subscriberType");
732 Map<String, Object> params = new HashMap<>();
733 params.put("global-customer-id", globalCustomerId);
734 params.put("subscriber-name", subscriberName);
735 params.put("subscriber-type", subscriberType);
736 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
737 intentApiService.addCustomer(globalCustomerId, requestBody).execute();
741 public IntentInstance createIntentInstance(Object body,String businessInstanceId, String businessInstance, String type) {
742 IntentInstance instance = new IntentInstance();
743 if (IntentConstant.MODEL_TYPE_CCVPN.equals(type)) {
744 assembleIntentInstanceFormCCVPNInfo(instance, body);
746 else if (IntentConstant.MODEL_TYPE_5GS.equals(type)) {
747 assembleIntentInstanceFormSliceInfo(instance, body);
749 instance.setIntentSource(type);
750 instance.setBusinessInstanceId(businessInstanceId);
751 instance.setBusinessInstance(businessInstance);
752 Session session = getSession();
753 Transaction tx = null;
755 tx = session.beginTransaction();
756 session.save(instance);
759 } catch (Exception e) {
763 logger.error("createIntentInstance Details:" + e.getMessage());
770 private IntentInstance assembleIntentInstanceFormCCVPNInfo(IntentInstance instance, Object body) {
771 JSONObject jsonObject = new JSONObject((Map) body);
772 String intent_content = jsonObject.getString("intentContent");
773 jsonObject.remove("intentContent");
774 instance.setIntentConfig(jsonObject.toJSONString());
775 instance.setIntentContent(intent_content);
776 instance.setIntentName(jsonObject.getString("name"));
780 private IntentInstance assembleIntentInstanceFormSliceInfo(IntentInstance instance, Object body) {
781 JSONObject jsonObject = new JSONObject((Map) body);
782 JSONObject slicingOrderInfo = jsonObject.getJSONObject("slicing_order_info");
783 String intent_content = slicingOrderInfo.getString("intentContent");
784 slicingOrderInfo.remove("intentContent");
785 instance.setIntentConfig(slicingOrderInfo.toJSONString());
786 instance.setIntentContent(intent_content);
787 instance.setIntentName(slicingOrderInfo.getString("name"));
793 public void deleteIntent(int id) {
794 Transaction tx = null;
795 Session session = getSession();
797 IntentInstance intentInstance = (IntentInstance)session.createQuery("from IntentInstance where id = :id")
798 .setParameter("id", id).uniqueResult();
799 if (IntentConstant.MODEL_TYPE_CCVPN.equals(intentInstance.getIntentSource())) {
800 deleteIntentInstance(intentInstance.getBusinessInstanceId());
802 resourceMgtService.terminateSlicingService(intentInstance.getBusinessInstanceId());
806 tx = session.beginTransaction();
807 session.delete(intentInstance);
809 logger.info("delete IntentInstance OK, id=" + intentInstance.getId());
810 } catch (Exception e) {
814 logger.error("delete IntentInstance occur exception:"+e);
822 public void verifyIntent(int id) {
823 Session session = getSession();
824 IntentInstance instance = new IntentInstance();
826 String hql = "from IntentInstance where id = :id";
827 Query query = session.createQuery(hql).setParameter("id", id);
828 instance = (IntentInstance) query.uniqueResult();
830 } catch (Exception e) {
831 logger.error("verifyIntentInstance error. Details:" + e.getMessage());
838 public Page<IntentInstance> getIntentInstanceList(int currentPage, int pageSize) {
839 Page<IntentInstance> page = new Page<IntentInstance>();
840 int allRow = getIntentInstanceAllCount();
841 int offset = page.countOffset(currentPage, pageSize);
842 Session session = getSession();
844 String hql = "from IntentInstance order by id";
845 Query query = session.createQuery(hql);
846 query.setFirstResult(offset);
847 query.setMaxResults(pageSize);
848 List<IntentInstance> list= query.list();
849 page.setPageNo(currentPage);
850 page.setPageSize(pageSize);
851 page.setTotalRecords(allRow);
854 } catch (Exception e) {
855 logger.error("exception occurred while performing IntentInstanceServiceImpl getIntentInstanceList. Details:" + e.getMessage());
863 public ServiceResult createSlicingServiceWithIntent(Object slicingOrderBody) {
865 SlicingOrder slicingOrder = JSONObject.parseObject(JSONObject.toJSONString(slicingOrderBody), SlicingOrder.class);
866 ServiceResult serviceResult = slicingService.createSlicingService(slicingOrder);
867 ServiceCreateResult createResult = (ServiceCreateResult) serviceResult.getResult_body();
869 saveSlicingServiceToAAI(createResult.getService_id(), createResult.getOperation_id(), slicingOrder);
870 } catch (IOException e) {
871 logger.error("save 5g slice to AAI fail!");
872 throw new RuntimeException("save 5g slice to AAI fail!", e);
874 createIntentInstance(slicingOrderBody,createResult.getService_id(), slicingOrder.getSlicing_order_info().getName(), IntentConstant.MODEL_TYPE_5GS);
875 return serviceResult;
879 public int updateCCVPNInstance(CCVPNInstance instance) {
880 Session session = getSession();
881 Transaction tx = null;
883 if (null == instance){
884 logger.error("instance is null!");
887 instance.setResourceInstanceId("cll-"+instance.getInstanceId());
889 CCVPNInstance ccvpnInstance = (CCVPNInstance)session.createQuery("from CCVPNInstance where instanceId = :instanceId")
890 .setParameter("instanceId", instance.getInstanceId()).uniqueResult();
891 ccvpnInstance.setAccessPointOneBandWidth(instance.getAccessPointOneBandWidth());
892 saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + ccvpnInstance.getInstanceId(), ccvpnInstance);
894 tx = session.beginTransaction();
895 session.update(ccvpnInstance);
898 } catch (Exception e) {
902 logger.error("Details:" + e.getMessage());
909 public int getIntentInstanceAllCount() {
910 Session session = getSession();
912 String count="select count(*) from IntentInstance";
913 Query query = session.createQuery(count);
914 long q=(long)query.uniqueResult();
916 } catch (Exception e) {
917 logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
924 public void addSubscription() throws IOException {
925 Properties environment = getProperties();
926 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
927 String serviceType = environment.getProperty("ccvpn.serviceType");
928 Response<JSONObject> querySubscription = intentApiService.querySubscription(globalCustomerId, serviceType).execute();
929 if (querySubscription.isSuccessful()) {
932 Map<String, Object> params = new HashMap<>();
933 params.put("service-type", serviceType);
934 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
935 intentApiService.addSubscription(globalCustomerId, serviceType, requestBody).execute();
938 public Properties getProperties() throws IOException {
939 String slicingPath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "ccvpn.properties";
940 InputStream inputStream = new FileInputStream(new File(slicingPath));
941 Properties environment = new Properties();
942 environment.load(inputStream);
947 public void saveIntentInstanceToAAI(String serviceInstanceId, CCVPNInstance instance) throws IOException {
950 Properties environment = getProperties();
951 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
952 String serviceType = environment.getProperty("ccvpn.serviceType");
953 String resourceVersion = null;
954 if (serviceInstanceId != null) {
955 Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
956 if (queryServiceInstance.isSuccessful()) {
957 JSONObject body = queryServiceInstance.body();
958 resourceVersion = body.getString("resource-version");
961 serviceInstanceId = IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId();
963 JSONObject environmentContext = JSONObject.parseObject(JSONObject.toJSONString(instance));
964 environmentContext.put("resourceInstanceId",instance.getResourceInstanceId());
966 Map<String, Object> params = new HashMap<>();
967 params.put("service-instance-id", serviceInstanceId);
968 params.put("service-instance-name", instance.getName());
969 params.put("service-type", IntentConstant.MODEL_TYPE_CCVPN);
970 params.put("environment-context", environmentContext.toJSONString());
971 params.put("service-instance-location-id", instance.getResourceInstanceId());
972 params.put("bandwidth-total", instance.getAccessPointOneBandWidth());
973 params.put("data-owner", IntentConstant.INTENT_INSTANCE_DATA_OWNER);
974 if (resourceVersion != null) {
975 params.put("resource-version",resourceVersion);
977 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
978 intentApiService.saveServiceInstance(globalCustomerId,serviceType,serviceInstanceId,requestBody).execute();
981 public void deleteIntentInstanceToAAI(String serviceInstanceId) throws IOException {
984 Properties environment = getProperties();
985 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
986 String serviceType = environment.getProperty("ccvpn.serviceType");
987 if (serviceInstanceId == null) {
990 Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
991 if (queryServiceInstance.isSuccessful()) {
992 JSONObject body = queryServiceInstance.body();
993 String resourceVersion = body.getString("resource-version");
994 intentApiService.deleteServiceInstance(globalCustomerId,serviceType,serviceInstanceId,resourceVersion).execute();
999 public void saveSlicingServiceToAAI(String serviceId, String operationId, SlicingOrder slicingOrder) throws IOException {
1002 Properties environment = getProperties();
1003 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
1004 String serviceType = environment.getProperty("ccvpn.serviceType");
1005 SlicingOrderDetail slicingOrderInfo = slicingOrder.getSlicing_order_info();
1006 JSONObject environmentContext = JSONObject.parseObject(JSONObject.toJSONString(slicingOrderInfo));
1008 Map<String, Object> params = new HashMap<>();
1009 params.put("service-instance-id", serviceId);
1010 params.put("service-instance-name", slicingOrderInfo.getName());
1011 params.put("service-type", IntentConstant.MODEL_TYPE_5GS);
1012 params.put("environment-context", environmentContext.toJSONString());
1013 params.put("service-operation-id", operationId);
1014 params.put("data-rate-uplink", slicingOrderInfo.getExpDataRateUL());
1015 params.put("data-rate-downlink", slicingOrderInfo.getExpDataRateDL());
1016 params.put("latency", slicingOrderInfo.getLatency());
1017 params.put("max-number-of-ues", slicingOrderInfo.getMaxNumberofUEs());
1018 params.put("mobility", slicingOrderInfo.getUEMobilityLevel());
1019 params.put("resource-sharing-level", slicingOrderInfo.getResourceSharingLevel());
1020 params.put("data-owner", IntentConstant.INTENT_INSTANCE_DATA_OWNER);
1021 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
1022 intentApiService.saveServiceInstance(globalCustomerId,serviceType,serviceId,requestBody).execute();