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", "true");
209 additionalProperties.put("serviceInstanceID", "cll-" + instance.getInstanceId());
210 List<Map<String, Object>> transportNetworks = new ArrayList<>();
211 Map<String, Object> transportNetwork = new HashMap<>();
212 transportNetwork.put("id", "");
213 Map<String, Object> sla = new HashMap<>();
214 sla.put("latency", "2");
215 sla.put("maxBandwidth", instance.getAccessPointOneBandWidth());
216 List<Map<String, Object>> connectionLinks = new ArrayList<>();
217 Map<String, Object> connectionLink = new HashMap<>();
218 connectionLink.put("name", "");
219 connectionLink.put("transportEndpointA", instance.getAccessPointOneName());
220 connectionLink.put("transportEndpointB", instance.getCloudPointName());
221 connectionLinks.add(connectionLink);
222 if (instance.getProtectStatus() == 1) {
223 sla.put("protectionType", instance.getProtectionType());
224 connectionLink.put("transportEndpointBProtection", instance.getProtectionCloudPointName());
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") * 1000;
408 InstancePerformance instancePerformance = new InstancePerformance();
409 instancePerformance.setMaxBandwidth(maxBandwidth);
410 instancePerformance.setResourceInstanceId(instance.getResourceInstanceId());
411 instancePerformance.setJobId(instance.getJobId());
412 instancePerformance.setDate(new Date());
414 Response<JSONObject> metadatumResponse = intentApiService.getInstanceBandwidth(serviceInstanceId).execute();
415 if (!metadatumResponse.isSuccessful()) {
416 logger.error("get Intent-Instance metadatum error:" + metadatumResponse.toString());
419 logger.debug("get Intent-Instance metadatum ok: instance id:" + instance.getInstanceId() + ", metadatum info:" + metadatumResponse.toString());
421 JSONObject metadatum = metadatumResponse.body();
422 JSONArray metadatumArr = metadatum.getJSONArray("metadatum");
424 for (int i = 0; i < metadatumArr.size(); i++) {
425 if (metaval == -1 || metaval > metadatumArr.getJSONObject(i).getIntValue("metaval")) {
426 metaval = metadatumArr.getJSONObject(i).getIntValue("metaval");
429 instancePerformance.setBandwidth(metaval);
431 Session session = getSession();
432 Transaction tx = null;
434 tx = session.beginTransaction();
435 session.save(instancePerformance);
437 } catch (Exception e) {
441 logger.error("Details:" + e.getMessage());
451 public void deleteIntentInstance(String instanceId) {
452 CCVPNInstance result = null;
453 Session session = getSession();
456 result = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
457 .setParameter("instanceId", instanceId).uniqueResult();
458 logger.info("get CCVPNInstance OK, id=" + instanceId);
460 } catch (Exception e) {
461 logger.error("getodel occur exception:"+e);
467 String serviceInstanceId = result.getResourceInstanceId();
468 deleteInstanceToSO(serviceInstanceId);
469 deleteIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-"+instanceId);
470 deleteInstance(result);
471 }catch (Exception e) {
472 logger.error("delete instance to SO error :" + e);
477 private void deleteInstanceToSO(String serviceInstanceId) throws IOException {
478 JSONObject params = new JSONObject();
479 params.put("serviceInstanceID", serviceInstanceId);
480 params.put("globalSubscriberId", "IBNCustomer");
481 params.put("subscriptionServiceType", "IBN");
482 params.put("serviceType", "CLL");
483 JSONObject additionalProperties = new JSONObject();
484 additionalProperties.put("enableSdnc", "true");
485 params.put("additionalProperties", additionalProperties);
486 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
487 intentApiService.deleteIntentInstance(requestBody).execute();
489 private String deleteInstance(CCVPNInstance instance) {
490 Transaction tx = null;
492 Session session = getSession();
494 tx = session.beginTransaction();
496 session.delete(instance);
498 logger.info("delete instance OK, id=" + instance.getInstanceId());
501 } catch (Exception e) {
505 logger.error("delete instance occur exception:"+e);
514 public void activeIntentInstance(String instanceId) {
515 CCVPNInstance instance = null;
516 Session session = getSession();
517 Transaction tx = null;
520 instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId and status = :status")
521 .setParameter("instanceId", instanceId).setParameter("status", "3").uniqueResult();
522 logger.info("get instance OK, id=" + instanceId);
524 if (null == instance) {
525 logger.error("instance is null!");
529 String jobId = createIntentInstanceToSO(instance);
530 instance.setStatus("0");
531 instance.setJobId(jobId);
532 tx = session.beginTransaction();
533 session.save(instance);
536 }catch (Exception e) {
540 logger.error("active instance to SO error :" + e);
546 public void invalidIntentInstance(String instanceId) {
547 CCVPNInstance instance = null;
548 Session session = getSession();
549 Transaction tx = null;
551 instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
552 .setParameter("instanceId", instanceId).uniqueResult();
553 logger.info("get instance OK, id=" + instanceId);
555 if (null == instance) {
556 logger.error("instance is null!");
559 deleteInstanceToSO(instance.getInstanceId());
560 instance.setStatus("3");
561 tx = session.beginTransaction();
562 session.save(instance);
566 }catch (Exception e) {
570 logger.error("invalid instance to SO error :" + e);
577 public Map<String, Object> queryInstancePerformanceData(String instanceId) {
578 Session session = getSession();
580 String hql = "from CCVPNInstance i, InstancePerformance p where i.resourceInstanceId = p.resourceInstanceId and i.instanceId = :instanceId and i.deleteState = 0 order by p.date";
581 Query query = session.createQuery(hql).setParameter("instanceId", instanceId);
582 List<Object[]> queryResult= query.list();
583 List<String> date = new ArrayList<>();
584 List<Integer> bandwidth = new ArrayList<>();
585 List<Integer> maxBandwidth = new ArrayList<>();
586 SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
587 for (int i = queryResult.size() > 50? queryResult.size() - 50 : 0; i < queryResult.size(); i++) {
588 Object[] o = queryResult.get(i);
589 InstancePerformance performance = (InstancePerformance) o[1];
590 date.add(ft.format(performance.getDate()));
591 bandwidth.add(performance.getBandwidth());
592 maxBandwidth.add(performance.getMaxBandwidth());
594 Map<String, Object> xAxis = new HashMap<>();
595 xAxis.put("data",date);
596 Map<String, Object> bandwidthData = new HashMap<>();
597 bandwidthData.put("data",bandwidth);
598 Map<String, Object> maxBandwidthData = new HashMap<>();
599 maxBandwidthData.put("data",maxBandwidth);
600 List<Map<String, Object>> series = new ArrayList<>();
601 series.add(bandwidthData);
602 series.add(maxBandwidthData);
604 Map<String, Object> result = new HashMap<>();
605 result.put("xAxis", xAxis);
606 result.put("series", series);
609 }catch (Exception e) {
610 logger.error("invalid instance to SO error :" + e);
618 public Object queryAccessNodeInfo() throws IOException {
619 Map<String, Object> result = new HashMap<>();
620 List<String> accessNodeList = new ArrayList<>();
621 List<String> cloudAccessNodeList = new ArrayList<>();
622 Response<JSONObject> response = intentApiService.queryNetworkRoute().execute();
623 if (!response.isSuccessful()) {
624 logger.error(response.toString());
625 throw new RuntimeException("Query Access Node Info Error");
627 JSONObject body = response.body();
628 JSONArray data = body.getJSONArray("network-route");
629 for (int i = 0; i<data.size(); i++) {
630 JSONObject nodeInfo = data.getJSONObject(i);
631 if ("ROOT".equals(nodeInfo.getString("type"))) {
632 cloudAccessNodeList.add(nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
635 accessNodeList.add(nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
637 IntentConstant.NetWorkNodeAlias.put(nodeInfo.getString("route-id"), nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
639 result.put("accessNodeList",accessNodeList);
640 result.put("cloudAccessNodeList",cloudAccessNodeList);
645 public JSONObject getInstanceStatus(JSONArray ids) {
646 Session session = getSession();
648 JSONObject result = new JSONObject();
649 JSONArray instanceInfos = new JSONArray();
650 String hql = "from CCVPNInstance i where i.instanceId in (:ids)";
651 Query query = session.createQuery(hql).setParameter("ids", ids);
652 List<CCVPNInstance> queryResult= query.list();
653 if (queryResult != null && queryResult.size() > 0) {
654 for (CCVPNInstance instance : queryResult) {
655 JSONObject instanceInfo = new JSONObject();
656 instanceInfo.put("id", instance.getInstanceId());
657 instanceInfo.put("status", instance.getStatus());
658 instanceInfos.add(instanceInfo);
661 result.put("IntentInstances",instanceInfos);
664 } catch (Exception e) {
665 logger.error("get Instance status error : " + e.getMessage());
673 public String formatBandwidth(String strValue) {
675 Pattern pattern = Pattern.compile("(\\d+)([\\w ]*)");
676 Matcher matcher = pattern.matcher(strValue);
680 if (matcher.matches()) {
681 dataRate = Integer.parseInt(matcher.group(1));
682 String company = matcher.group(2).trim().toLowerCase();
683 if (GB_COMPANY.contains(company)) {
684 dataRate = dataRate * 1000;
686 else if (!MB_COMPANY.contains(company)) {
689 dataRate = dataRate < MIN_BANDWIDTH ? MIN_BANDWIDTH : (dataRate > MAX_BANDWIDTH ? MAX_BANDWIDTH : dataRate);
696 public String formatCloudPoint(String cloudPoint) {
697 String cloudPointAlias = "";
698 switch (cloudPoint) {
700 cloudPointAlias = "tranportEp_dst_ID_212_1";
703 return cloudPointAlias;
706 public String formatAccessPoint(String accessPoint) {
707 String accessPointAlias = "";
708 switch (accessPoint) {
710 accessPointAlias = "tranportEp_src_ID_111_1";
713 accessPointAlias = "tranportEp_src_ID_111_2";
715 case "Access three" :
716 accessPointAlias = "tranportEp_src_ID_113_1";
719 return accessPointAlias;
722 public void addCustomer() throws IOException {
723 Properties environment = getProperties();
724 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
725 Response<JSONObject> queryCustomerResponse = intentApiService.queryCustomer(globalCustomerId).execute();
726 if (queryCustomerResponse.isSuccessful()) {
729 String subscriberName = environment.getProperty("ccvpn.subscriberName");
730 String subscriberType = environment.getProperty("ccvpn.subscriberType");
731 Map<String, Object> params = new HashMap<>();
732 params.put("global-customer-id", globalCustomerId);
733 params.put("subscriber-name", subscriberName);
734 params.put("subscriber-type", subscriberType);
735 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
736 intentApiService.addCustomer(globalCustomerId, requestBody).execute();
740 public IntentInstance createIntentInstance(Object body,String businessInstanceId, String businessInstance, String type) {
741 IntentInstance instance = new IntentInstance();
742 if (IntentConstant.MODEL_TYPE_CCVPN.equals(type)) {
743 assembleIntentInstanceFormCCVPNInfo(instance, body);
745 else if (IntentConstant.MODEL_TYPE_5GS.equals(type)) {
746 assembleIntentInstanceFormSliceInfo(instance, body);
748 instance.setIntentSource(type);
749 instance.setBusinessInstanceId(businessInstanceId);
750 instance.setBusinessInstance(businessInstance);
751 Session session = getSession();
752 Transaction tx = null;
754 tx = session.beginTransaction();
755 session.save(instance);
758 } catch (Exception e) {
762 logger.error("createIntentInstance Details:" + e.getMessage());
769 private IntentInstance assembleIntentInstanceFormCCVPNInfo(IntentInstance instance, Object body) {
770 JSONObject jsonObject = new JSONObject((Map) body);
771 String intent_content = jsonObject.getString("intentContent");
772 jsonObject.remove("intentContent");
773 instance.setIntentConfig(jsonObject.toJSONString());
774 instance.setIntentContent(intent_content);
775 instance.setIntentName(jsonObject.getString("name"));
779 private IntentInstance assembleIntentInstanceFormSliceInfo(IntentInstance instance, Object body) {
780 JSONObject jsonObject = new JSONObject((Map) body);
781 JSONObject slicingOrderInfo = jsonObject.getJSONObject("slicing_order_info");
782 String intent_content = slicingOrderInfo.getString("intentContent");
783 slicingOrderInfo.remove("intentContent");
784 instance.setIntentConfig(slicingOrderInfo.toJSONString());
785 instance.setIntentContent(intent_content);
786 instance.setIntentName(slicingOrderInfo.getString("name"));
792 public void deleteIntent(int id) {
793 Transaction tx = null;
794 Session session = getSession();
796 IntentInstance intentInstance = (IntentInstance)session.createQuery("from IntentInstance where id = :id")
797 .setParameter("id", id).uniqueResult();
798 if (IntentConstant.MODEL_TYPE_CCVPN.equals(intentInstance.getIntentSource())) {
799 deleteIntentInstance(intentInstance.getBusinessInstanceId());
801 resourceMgtService.terminateSlicingService(intentInstance.getBusinessInstanceId());
805 tx = session.beginTransaction();
806 session.delete(intentInstance);
808 logger.info("delete IntentInstance OK, id=" + intentInstance.getId());
809 } catch (Exception e) {
813 logger.error("delete IntentInstance occur exception:"+e);
821 public void verifyIntent(int id) {
822 Session session = getSession();
823 IntentInstance instance = new IntentInstance();
825 String hql = "from IntentInstance where id = :id";
826 Query query = session.createQuery(hql).setParameter("id", id);
827 instance = (IntentInstance) query.uniqueResult();
829 } catch (Exception e) {
830 logger.error("verifyIntentInstance error. Details:" + e.getMessage());
837 public Page<IntentInstance> getIntentInstanceList(int currentPage, int pageSize) {
838 Page<IntentInstance> page = new Page<IntentInstance>();
839 int allRow = getIntentInstanceAllCount();
840 int offset = page.countOffset(currentPage, pageSize);
841 Session session = getSession();
843 String hql = "from IntentInstance order by id";
844 Query query = session.createQuery(hql);
845 query.setFirstResult(offset);
846 query.setMaxResults(pageSize);
847 List<IntentInstance> list= query.list();
848 page.setPageNo(currentPage);
849 page.setPageSize(pageSize);
850 page.setTotalRecords(allRow);
853 } catch (Exception e) {
854 logger.error("exception occurred while performing IntentInstanceServiceImpl getIntentInstanceList. Details:" + e.getMessage());
862 public ServiceResult createSlicingServiceWithIntent(Object slicingOrderBody) {
864 SlicingOrder slicingOrder = JSONObject.parseObject(JSONObject.toJSONString(slicingOrderBody), SlicingOrder.class);
865 ServiceResult serviceResult = slicingService.createSlicingService(slicingOrder);
866 ServiceCreateResult createResult = (ServiceCreateResult) serviceResult.getResult_body();
868 createIntentInstance(slicingOrderBody,createResult.getService_id(), slicingOrder.getSlicing_order_info().getName(), IntentConstant.MODEL_TYPE_5GS);
869 return serviceResult;
873 public int updateCCVPNInstance(CCVPNInstance instance) {
874 Session session = getSession();
875 Transaction tx = null;
877 if (null == instance){
878 logger.error("instance is null!");
881 instance.setResourceInstanceId("cll-"+instance.getInstanceId());
883 CCVPNInstance ccvpnInstance = (CCVPNInstance)session.createQuery("from CCVPNInstance where instanceId = :instanceId")
884 .setParameter("instanceId", instance.getInstanceId()).uniqueResult();
885 ccvpnInstance.setAccessPointOneBandWidth(instance.getAccessPointOneBandWidth());
886 saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + ccvpnInstance.getInstanceId(), ccvpnInstance);
888 tx = session.beginTransaction();
889 session.update(ccvpnInstance);
892 } catch (Exception e) {
896 logger.error("Details:" + e.getMessage());
903 public int getIntentInstanceAllCount() {
904 Session session = getSession();
906 String count="select count(*) from IntentInstance";
907 Query query = session.createQuery(count);
908 long q=(long)query.uniqueResult();
910 } catch (Exception e) {
911 logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
918 public void addSubscription() throws IOException {
919 Properties environment = getProperties();
920 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
921 String serviceType = environment.getProperty("ccvpn.serviceType");
922 Response<JSONObject> querySubscription = intentApiService.querySubscription(globalCustomerId, serviceType).execute();
923 if (querySubscription.isSuccessful()) {
926 Map<String, Object> params = new HashMap<>();
927 params.put("service-type", serviceType);
928 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
929 intentApiService.addSubscription(globalCustomerId, serviceType, requestBody).execute();
932 public Properties getProperties() throws IOException {
933 String slicingPath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "ccvpn.properties";
934 InputStream inputStream = new FileInputStream(new File(slicingPath));
935 Properties environment = new Properties();
936 environment.load(inputStream);
941 public void saveIntentInstanceToAAI(String serviceInstanceId, CCVPNInstance instance) throws IOException {
944 Properties environment = getProperties();
945 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
946 String serviceType = environment.getProperty("ccvpn.serviceType");
947 String resourceVersion = null;
948 if (serviceInstanceId != null) {
949 Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
950 if (queryServiceInstance.isSuccessful()) {
951 JSONObject body = queryServiceInstance.body();
952 resourceVersion = body.getString("resource-version");
955 serviceInstanceId = IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId();
957 JSONObject environmentContext = JSONObject.parseObject(JSONObject.toJSONString(instance));
958 environmentContext.put("resourceInstanceId",instance.getResourceInstanceId());
960 Map<String, Object> params = new HashMap<>();
961 params.put("service-instance-id", serviceInstanceId);
962 params.put("service-instance-name", instance.getName());
963 params.put("service-type", IntentConstant.MODEL_TYPE_CCVPN);
964 params.put("environment-context", environmentContext.toJSONString());
965 params.put("service-instance-location-id", instance.getResourceInstanceId());
966 params.put("bandwidth-total", instance.getAccessPointOneBandWidth());
967 params.put("data-owner", IntentConstant.INTENT_INSTANCE_DATA_OWNER);
968 if (resourceVersion != null) {
969 params.put("resource-version",resourceVersion);
971 okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
972 intentApiService.saveServiceInstance(globalCustomerId,serviceType,serviceInstanceId,requestBody).execute();
975 public void deleteIntentInstanceToAAI(String serviceInstanceId) throws IOException {
978 Properties environment = getProperties();
979 String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
980 String serviceType = environment.getProperty("ccvpn.serviceType");
981 if (serviceInstanceId == null) {
984 Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
985 if (queryServiceInstance.isSuccessful()) {
986 JSONObject body = queryServiceInstance.body();
987 String resourceVersion = body.getString("resource-version");
988 intentApiService.deleteServiceInstance(globalCustomerId,serviceType,serviceInstanceId,resourceVersion).execute();