Merge branch 'recursive-orch'
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoCommonCoreNSSI.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2020  Telecom Italia
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.scripts
22
23 import com.fasterxml.jackson.databind.ObjectMapper
24 import org.camunda.bpm.engine.delegate.BpmnError
25 import org.camunda.bpm.engine.delegate.DelegateExecution
26 import org.json.JSONArray
27 import org.json.JSONObject
28 import org.onap.aai.domain.yang.v19.*
29 import org.onap.aaiclient.client.aai.AAIResourcesClient
30 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
31 import org.onap.aaiclient.client.aai.entities.Relationships
32 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
33 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
34 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
35 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
36 import org.onap.logging.filter.base.ONAPComponents
37 import org.onap.so.bpmn.common.scripts.*
38 import org.onap.so.bpmn.core.UrnPropertiesReader
39 import org.onap.so.bpmn.core.json.JsonUtils
40 import org.onap.so.client.HttpClient
41 import org.onap.so.db.request.beans.ResourceOperationStatus
42 import org.onap.so.serviceinstancebeans.*
43 import org.slf4j.Logger
44 import org.slf4j.LoggerFactory
45
46 import javax.ws.rs.NotFoundException
47 import javax.ws.rs.core.Response
48
49 import static org.apache.commons.lang3.StringUtils.isBlank
50
51 class DoCommonCoreNSSI extends AbstractServiceTaskProcessor {
52
53     private final String PREFIX ="DoCommonCoreNSSI"
54
55     private static final String SLICE_PROFILE_TEMPLATE = "{\"sliceProfileId\": \"%s\"}"
56
57     private static final Logger LOGGER = LoggerFactory.getLogger( DoCommonCoreNSSI.class)
58
59     private JsonUtils jsonUtil = new JsonUtils()
60     private ExceptionUtil exceptionUtil = new ExceptionUtil()
61     private RequestDBUtil requestDBUtil = new RequestDBUtil()
62
63     @Override
64     void preProcessRequest(DelegateExecution execution) {
65         LOGGER.debug("${getPrefix()} Start preProcessRequest")
66
67         def currentNSSI = execution.getVariable("currentNSSI")
68         if (!currentNSSI) {
69             currentNSSI = [:]
70         }
71
72         // NSSI ID
73         String nssiId = execution.getVariable("serviceInstanceID")
74         if (isBlank(nssiId)) {
75             String msg = "NSSI service instance id is null"
76             LOGGER.error(msg)
77             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
78         }
79         else {
80             currentNSSI['nssiId'] = nssiId
81         }
82
83         // NSI ID
84         String nsiId = execution.getVariable("nsiId")
85         if (isBlank(nsiId)) {
86             String msg = "nsiId is null"
87             LOGGER.error(msg)
88             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
89         }
90         else {
91             currentNSSI['nsiId'] = nsiId
92         }
93
94
95         // Slice Profile
96         String sliceProfile = execution.getVariable("sliceParams")
97         
98       /*  if(jsonUtil.jsonValueExists(execution.getVariable("sliceParams"), "sliceProfile")) {
99             sliceProfile = jsonUtil.getJsonValue(execution.getVariable("sliceParams"), "sliceProfile")
100         }
101         else { // In case of Deallocate flow or Modify flow with deletion of Slice Profile Instance
102             if(jsonUtil.jsonValueExists(execution.getVariable("sliceParams"), "sliceProfileId")) {
103                 sliceProfile = String.format(SLICE_PROFILE_TEMPLATE, jsonUtil.getJsonValue(execution.getVariable("sliceParams"), "sliceProfileId"))
104             }
105             else {
106                 String msg = "Either Slice Profile or Slice Profile Id should be provided"
107                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
108             }
109         } */
110
111         LOGGER.debug("sliceProfile=" + sliceProfile)
112         currentNSSI['sliceProfile'] = sliceProfile
113
114         // S-NSSAI
115         String strList = jsonUtil.getJsonValue(sliceProfile, "snssaiList")
116
117         if(strList != null) {
118             def snssaiList = jsonUtil.StringArrayToList(strList)
119
120             String sNssai = snssaiList.get(0)
121             currentNSSI['S-NSSAI'] = sNssai
122         }
123
124         LOGGER.debug("S-NSSAI=" + currentNSSI['S-NSSAI'])
125
126         // Slice Profile id
127         String sliceProfileId = jsonUtil.getJsonValue(sliceProfile, "sliceProfileId")
128         currentNSSI['sliceProfileId'] = sliceProfileId
129
130         execution.setVariable("currentNSSI", currentNSSI)
131
132         LOGGER.debug("***** ${getPrefix()} Exit preProcessRequest")
133     }
134
135
136     /**
137      * Queries Network Service Instance in AAI
138      * @param execution
139      */
140     void getNetworkServiceInstance(DelegateExecution execution) {
141         LOGGER.debug("${getPrefix()} Start getNetworkServiceInstance")
142
143         AAIResourcesClient client = getAAIClient()
144
145         def currentNSSI = execution.getVariable("currentNSSI")
146
147         String nssiId = currentNSSI['nssiId']
148
149         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
150         Optional<ServiceInstance> nssiOpt = client.get(ServiceInstance.class, nssiUri)
151
152         if (nssiOpt.isPresent()) {
153             ServiceInstance nssi = nssiOpt.get()
154             currentNSSI['nssi'] = nssi
155
156             ServiceInstance networkServiceInstance = handleNetworkInstance(execution, nssiId, nssiUri, client)
157             currentNSSI['networkServiceInstance'] = networkServiceInstance
158         }
159         else {
160             String msg = String.format("NSSI %s not found in AAI", nssiId)
161             LOGGER.error(msg)
162             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
163         }
164
165         LOGGER.debug("${getPrefix()} Exit getNetworkServiceInstance")
166     }
167
168
169     /**
170      * Handles Network Service
171      * @param nssiId
172      * @param nssiUri
173      * @param client
174      * @return Network Service Instance
175      */
176     private ServiceInstance handleNetworkInstance(DelegateExecution execution, String nssiId, AAIResourceUri nssiUri, AAIResourcesClient client ) {
177         LOGGER.debug("${getPrefix()} Start handleNetworkInstance")
178
179         ServiceInstance networkServiceInstance = null
180
181         def currentNSSI = execution.getVariable("currentNSSI")
182
183         AAIResultWrapper wrapper = client.get(nssiUri)
184         Optional<Relationships> relationships = wrapper.getRelationships()
185
186         if (relationships.isPresent()) {
187             for (AAIResourceUri networkServiceInstanceUri : relationships.get().getRelatedUris(Types.SERVICE_INSTANCE)) {
188                 Optional<ServiceInstance> networkServiceInstanceOpt = client.get(ServiceInstance.class, networkServiceInstanceUri)
189                 if (networkServiceInstanceOpt.isPresent()) {
190                     networkServiceInstance = networkServiceInstanceOpt.get()
191
192                     if (networkServiceInstance.getServiceRole() == null /* WorkAround */ ||  networkServiceInstance.getServiceRole() == "Network Service") { // Network Service role
193                         currentNSSI['networkServiceInstanceUri'] = networkServiceInstanceUri
194                         break
195                     }
196                 }
197                 else {
198                     String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
199                     LOGGER.error(msg)
200                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
201                 }
202             }
203
204             if (currentNSSI['networkServiceInstanceUri'] == null) {
205                 String msg = String.format("Network Service Instance URI is null")
206                 LOGGER.error(msg)
207                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
208             }
209         }
210         else {
211             String msg = String.format("No relationship presented for NSSI %s in AAI", nssiId)
212             LOGGER.error(msg)
213             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
214         }
215
216         if(networkServiceInstance == null) {
217             String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
218             LOGGER.error(msg)
219             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
220         }
221
222         LOGGER.debug("${getPrefix()} Exit handleNetworkInstance")
223
224         return networkServiceInstance
225     }
226
227
228     /**
229      * Queries constitute VNF from Network Service Instance
230      * @param execution
231      */
232     void getConstituteVNFFromNetworkServiceInst(DelegateExecution execution) {
233         LOGGER.debug("${getPrefix()} Start getConstituteVNFFromNetworkServiceInst")
234
235         def currentNSSI = execution.getVariable("currentNSSI")
236
237         AAIResourcesClient client = getAAIClient()
238
239         AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
240         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri);
241         Optional<Relationships> relationships = wrapper.getRelationships()
242
243         if (relationships.isPresent()) {
244             for (AAIResourceUri constituteVnfUri : relationships.get().getRelatedUris(Types.GENERIC_VNF)) {
245                 currentNSSI['constituteVnfUri'] = constituteVnfUri
246                 Optional<GenericVnf> constituteVnfOpt = client.get(GenericVnf.class, constituteVnfUri)
247                 if(constituteVnfOpt.isPresent()) {
248                     GenericVnf constituteVnf = constituteVnfOpt.get()
249                     currentNSSI['constituteVnf'] = constituteVnf
250                 }
251                 else {
252                     String msg = String.format("No constitute VNF found for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
253                     LOGGER.error(msg)
254                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
255                 }
256
257                 break  // Should be only one constitute VNF
258             }
259         }
260         else {
261             String msg = String.format("No relationship presented for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
262             LOGGER.error(msg)
263             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
264         }
265
266         LOGGER.debug("${getPrefix()} Exit getConstituteVNFFromNetworkServiceInst")
267
268     }
269
270
271     /**
272      * Invoke PUT Service Instance API
273      * @param execution
274      */
275     void invokePUTServiceInstance(DelegateExecution execution) {
276         LOGGER.debug("${getPrefix()} Start invokePUTServiceInstance")
277
278         def currentNSSI = execution.getVariable("currentNSSI")
279
280         try {
281             //url:/onap/so/infra/serviceInstantiation/v7/serviceInstances/{serviceInstanceId}"
282             def nsmfЕndPoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution) // ???
283
284             ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
285
286             GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
287
288             // http://so.onap:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances/de6a0aa2-19f2-41fe-b313-a5a9f159acd7/vnfs/3abbb373-8d33-4977-aa4b-2bfee496b6d5
289             String url = String.format("${nsmfЕndPoint}/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s", networkServiceInstance.getServiceInstanceId(), constituteVnf.getVnfId())
290
291             String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
292
293             String basicAuth =  UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution)
294
295             def authHeader = utils.getBasicAuth(basicAuth, msoKey) // ""
296          /*   String basicAuthValue = encryptBasicAuth(basicAuth, msoKey) //utils.encrypt(basicAuth, msoKey)
297
298             String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msoKey) //utils.getBasicAuth(basicAuthValue, msoKey)
299
300             String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
301             if(errorCode == null || errorCode.isEmpty()) { // No error
302                 authHeader = responseAuthHeader
303             }
304             else {
305                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
306             } */
307
308             def requestDetails = ""
309
310             String prepareRequestDetailsResponse = prepareRequestDetails(execution)
311             LOGGER.debug("invokePUTServiceInstance: prepareRequestDetailsResponse=" + prepareRequestDetailsResponse)
312
313             String errorCode = jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorCode")
314             LOGGER.debug("invokePUTServiceInstance: errorCode=" + errorCode)
315             if(errorCode == null || errorCode.isEmpty()) { // No error
316                 requestDetails = prepareRequestDetailsResponse
317             }
318             else {
319                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorMessage"))
320             }
321
322             String callPUTServiceInstanceResponse = callPUTServiceInstance(url, authHeader, requestDetails)
323
324             String macroOperationId = jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "requestReferences.requestId")
325             String requestSelfLink = jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "requestReferences.requestSelfLink")
326
327             execution.setVariable("macroOperationId",  macroOperationId)
328             execution.setVariable("requestSelfLink", requestSelfLink)
329             currentNSSI['requestSelfLink'] = requestSelfLink
330
331         } catch (any) {
332             String msg = "Exception in ${getPrefix()}.invokePUTServiceInstance. " + any.getCause()
333             LOGGER.error(msg)
334             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
335         }
336
337         LOGGER.debug("${getPrefix()} Exit invokePUTServiceInstance")
338     }
339
340
341     String callPUTServiceInstance(String url, String authHeader, String requestDetailsStr) {
342         LOGGER.debug("${getPrefix()} Start callPUTServiceInstance")
343
344         String errorCode = ""
345         String errorMessage = ""
346         String response
347
348         LOGGER.debug("callPUTServiceInstance: url = " + url)
349         LOGGER.debug("callPUTServiceInstance: authHeader = " + authHeader)
350
351         try {
352             HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.SO)
353             httpClient.addAdditionalHeader("Authorization", authHeader)
354             httpClient.addAdditionalHeader("Accept", "application/json")
355
356             Response httpResponse = httpClient.put(requestDetailsStr)
357
358             int soResponseCode = httpResponse.getStatus()
359             if (soResponseCode >= 200 && soResponseCode < 204 && httpResponse.hasEntity()) {
360                 response = httpResponse.readEntity(String.class)
361
362                 LOGGER.debug("callPUTServiceInstance: response = " + response)
363             }
364             else {
365                 errorCode = 500
366                 errorMessage = "Response code is " + soResponseCode
367
368                 response =  "{\n" +
369                         " \"errorCode\": \"${errorCode}\",\n" +
370                         " \"errorMessage\": \"${errorMessage}\"\n" +
371                         "}"
372             }
373         }
374         catch (any) {
375             String msg = "Exception in ${getPrefix()}.invokePUTServiceInstance. " + any.getCause()
376             LOGGER.error(msg)
377
378             response =  "{\n" +
379                     " \"errorCode\": \"7000\",\n" +
380                     " \"errorMessage\": \"${msg}\"\n" +
381                     "}"
382
383         }
384
385         LOGGER.debug("${getPrefix()} Exit callPUTServiceInstance")
386
387         return response
388
389     }
390
391
392     /**
393      * Prepare model info
394      * @param execution
395      * @param requestDetails
396      * @return ModelInfo
397      */
398     ModelInfo prepareModelInfo(DelegateExecution execution) {
399         LOGGER.debug("${getPrefix()} Start prepareModelInfo")
400
401         def currentNSSI = execution.getVariable("currentNSSI")
402         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
403
404         ModelInfo modelInfo = new ModelInfo()
405
406         modelInfo.setModelType(ModelType.service)
407         modelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
408
409         AAIResourcesClient client = getAAIClient()
410
411         AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(networkServiceInstance.getModelInvariantId()).modelVer(networkServiceInstance.getModelVersionId()))
412         Optional<ModelVer> modelVerOpt = client.get(ModelVer.class, modelVerUrl)
413
414         if (modelVerOpt.isPresent()) {
415             modelInfo.setModelVersionId(modelVerOpt.get().getModelVersionId())
416             modelInfo.setModelName(modelVerOpt.get().getModelName())
417             modelInfo.setModelVersion(modelVerOpt.get().getModelVersion())
418         }
419
420         LOGGER.debug("${getPrefix()} Exit prepareModelInfo")
421
422         return modelInfo
423     }
424
425
426     /**
427      * Prepares subscriber info
428      * @param execution
429      * @return SubscriberInfo
430      */
431     SubscriberInfo prepareSubscriberInfo(DelegateExecution execution) {
432         LOGGER.debug("${getPrefix()} Start prepareSubscriberInfo")
433
434         def currentNSSI = execution.getVariable("currentNSSI")
435
436         String globalSubscriberId = execution.getVariable("globalSubscriberId")
437
438         String subscriberName = execution.getVariable("subscriberName")
439
440         SubscriberInfo subscriberInfo = new SubscriberInfo()
441         subscriberInfo.setGlobalSubscriberId(globalSubscriberId)
442         subscriberInfo.setSubscriberName(subscriberName)
443
444         /*
445         AAIResourcesClient client = getAAIClient()
446
447         Customer customer = null
448
449         AAIResourceUri networkServiceInstanceUri = currentNSSI['networkServiceInstanceUri']
450         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
451         Optional<Relationships> serviceSubscriptionRelationshipsOps = wrapper.getRelationships()
452         if(serviceSubscriptionRelationshipsOps.isPresent()) {
453             List<AAIResourceUri> serviceSubscriptionRelatedAAIUris = serviceSubscriptionRelationshipsOps.get().getRelatedUris(Types.SERVICE_SUBSCRIPTION)
454             if(!(serviceSubscriptionRelatedAAIUris == null || serviceSubscriptionRelatedAAIUris.isEmpty())) {
455                 AAIResourceUri serviceSubscriptionUri = serviceSubscriptionRelatedAAIUris.get(0) // Many-To-One relation
456                 Optional<ServiceSubscription> serviceSubscriptionOpt = client.get(ServiceSubscription.class, serviceSubscriptionUri)
457
458                 if(serviceSubscriptionOpt.isPresent()) {
459                     currentNSSI['serviceSubscription'] = serviceSubscriptionOpt.get()
460                 }
461
462                 wrapper = client.get(serviceSubscriptionUri)
463                 Optional<Relationships> customerRelationshipsOps = wrapper.getRelationships()
464                 if(customerRelationshipsOps.isPresent()) {
465                     List<AAIResourceUri> customerRelatedAAIUris = customerRelationshipsOps.get().getRelatedUris(Types.CUSTOMER)
466                     if(!(customerRelatedAAIUris == null || customerRelatedAAIUris.isEmpty())) {
467                         Optional<Customer> customerOpt = client.get(Customer.class, customerRelatedAAIUris.get(0)) // Many-To-One relation
468                         if(customerOpt.isPresent()) {
469                             customer = customerOpt.get()
470                             subscriberInfo.setSubscriberName(customer.getSubscriberName())
471                         }
472                     }
473                 }
474             }
475
476         } */
477
478         LOGGER.debug("${getPrefix()} Exit prepareSubscriberInfo")
479
480         return subscriberInfo
481     }
482
483
484     /**
485      * Prepares Request Info
486      * @param execution
487      * @return RequestInfo
488      */
489     RequestInfo prepareRequestInfo(DelegateExecution execution, ServiceInstance networkServiceInstance) {
490         LOGGER.debug("${getPrefix()} Start prepareRequestInfo")
491
492         def currentNSSI = execution.getVariable("currentNSSI")
493
494         String productFamilyId = execution.getVariable("productFamilyId")
495
496         RequestInfo requestInfo = new RequestInfo()
497
498         requestInfo.setInstanceName(networkServiceInstance.getServiceInstanceName())
499         requestInfo.setSource("VID")
500         requestInfo.setProductFamilyId(productFamilyId)
501         requestInfo.setRequestorId("NBI")
502
503         LOGGER.debug("${getPrefix()} Exit prepareRequestInfo")
504
505         return requestInfo
506     }
507
508
509     /**
510      * Prepares Model Info
511      * @param networkServiceInstance
512      * @param modelInfo
513      * @return ModelInfo
514      */
515     ModelInfo prepareServiceModelInfo(ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
516         LOGGER.debug("${getPrefix()} Start prepareServiceModelInfo")
517
518         ModelInfo serviceModelInfo = new ModelInfo()
519         serviceModelInfo.setModelType(ModelType.service)
520         serviceModelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
521
522         serviceModelInfo.setModelVersionId(modelInfo.getModelVersionId())
523         serviceModelInfo.setModelName(modelInfo.getModelName())
524         serviceModelInfo.setModelVersion(modelInfo.getModelVersion())
525
526         LOGGER.debug("${getPrefix()} Exit prepareServiceModelInfo")
527
528         return serviceModelInfo
529     }
530
531
532     /**
533      * Prepares Cloud configuration
534      * @param execution
535      * @return CloudConfiguration
536      */
537     CloudConfiguration prepareCloudConfiguration(DelegateExecution execution) {
538         LOGGER.debug("${getPrefix()} Start prepareCloudConfiguration")
539
540         def currentNSSI = execution.getVariable("currentNSSI")
541
542         CloudConfiguration cloudConfiguration = new CloudConfiguration()
543
544         AAIResourcesClient client = getAAIClient()
545
546         AAIResourceUri constituteVnfUri = currentNSSI['constituteVnfUri']
547
548         AAIResultWrapper wrapper = client.get(constituteVnfUri)
549         Optional<Relationships> cloudRegionRelationshipsOps = wrapper.getRelationships()
550
551         if(cloudRegionRelationshipsOps.isPresent()) {
552             List<AAIResourceUri> cloudRegionRelatedAAIUris = cloudRegionRelationshipsOps.get().getRelatedUris(Types.CLOUD_REGION)
553             if (!(cloudRegionRelatedAAIUris == null || cloudRegionRelatedAAIUris.isEmpty())) {
554                 AAIResourceUri cloudRegionRelatedAAIUri = cloudRegionRelatedAAIUris.get(0)
555                 currentNSSI['cloudRegionRelatedAAIUri'] = cloudRegionRelatedAAIUri
556
557                 Optional<CloudRegion> cloudRegionrOpt = client.get(CloudRegion.class, cloudRegionRelatedAAIUris.get(0))
558                 CloudRegion cloudRegion = null
559                 if (cloudRegionrOpt.isPresent()) {
560                     cloudRegion = cloudRegionrOpt.get()
561                     cloudConfiguration.setLcpCloudRegionId(cloudRegion.getCloudRegionId())
562
563                     if(cloudRegion.getTenants() != null && cloudRegion.getTenants().getTenant() != null) {
564                         for (Tenant tenant : cloudRegion.getTenants().getTenant()) {
565                             cloudConfiguration.setTenantId(tenant.getTenantId())
566                             cloudConfiguration.setTenantName(tenant.getTenantName())
567                             break // only one is required
568                         }
569                     }
570                     else {
571                         List<AAIResourceUri> tenantRelatedAAIUris = cloudRegionRelationshipsOps.get().getRelatedUris(Types.TENANT)
572                         if (!(tenantRelatedAAIUris == null || tenantRelatedAAIUris.isEmpty())) {
573                             Optional<Tenant> tenantOpt = client.get(Tenant.class, tenantRelatedAAIUris.get(0))
574                             Tenant tenant = null
575                             if (tenantOpt.isPresent()) {
576                                 tenant = tenantOpt.get()
577
578                                 LOGGER.debug("prepareCloudConfiguration: tenantId=" + tenant.getTenantId())
579                                 LOGGER.debug("prepareCloudConfiguration: tenantName=" + tenant.getTenantName())
580
581                                 cloudConfiguration.setTenantId(tenant.getTenantId())
582                                 cloudConfiguration.setTenantName(tenant.getTenantName())
583                             }
584                         }
585                     }
586
587                     cloudConfiguration.setCloudOwner(cloudRegion.getCloudOwner())
588                 }
589             }
590         }
591
592         LOGGER.debug("${getPrefix()} Exit prepareCloudConfiguration")
593
594         return cloudConfiguration
595     }
596
597
598     /**
599      * Prepares a list of VF Modules
600      * @param execution
601      * @param constituteVnf
602      * @return List<VfModules>
603      */
604     List<org.onap.so.serviceinstancebeans.VfModules> prepareVfModules(DelegateExecution execution, GenericVnf constituteVnf) {
605         LOGGER.debug("${getPrefix()} Start prepareVfModules")
606
607         AAIResourcesClient client = getAAIClient()
608
609         def currentNSSI = execution.getVariable("currentNSSI")
610
611         List<org.onap.so.serviceinstancebeans.VfModules> vfModuless = new ArrayList<>()
612
613         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
614
615         String networkServiceModelInvariantUuid = networkServiceInstance.getModelInvariantId()
616
617         String serviceVnfs="";
618         String msg=""
619         try{
620             CatalogDbUtils catalogDbUtils = getCatalogDbUtilsFactory().create()
621
622             String json = catalogDbUtils.getServiceResourcesByServiceModelInvariantUuidString(execution, networkServiceModelInvariantUuid)
623             LOGGER.debug("***** JSON IS: "+json)
624
625             serviceVnfs = jsonUtil.getJsonValue(json, "serviceResources.serviceVnfs") ?: ""
626
627             ObjectMapper mapper = new ObjectMapper()
628
629             List<Object> vnfList = mapper.readValue(serviceVnfs, List.class)
630             LOGGER.debug("vnfList:  "+vnfList)
631
632             Map vnfMap = vnfList.get(0)
633             ModelInfo vnfModelInfo = vnfMap.get("modelInfo")
634             vnfModelInfo.setModelCustomizationId(vnfModelInfo.getModelCustomizationUuid())
635             vnfModelInfo.setModelVersionId(vnfModelInfo.getModelId())
636             LOGGER.debug("vnfModelInfo "+vnfModelInfo)
637
638             //List of VFModules
639             List<Map<String, Object>> vfModuleList = vnfMap.get("vfModules")
640             LOGGER.debug("vfModuleList "+vfModuleList)
641
642             //List of VfModules
643             List<ModelInfo> vfModelInfoList = new ArrayList<>()
644
645             //Traverse VFModules List and add in vfModelInfoList
646             for (vfModule in vfModuleList) {
647                 ModelInfo vfModelInfo = vfModule.get("modelInfo")
648                 vfModelInfo.setModelCustomizationId(vfModelInfo.getModelCustomizationUuid())
649                 vfModelInfo.setModelVersionId(vfModelInfo.getModelId())
650                 LOGGER.debug("vfModelInfo "+vfModelInfo)
651                 vfModelInfoList.add(vfModelInfo)
652             }
653
654             for (ModelInfo vfModuleModelInfo : vfModelInfoList) {
655                 org.onap.so.serviceinstancebeans.VfModules vfModules = new org.onap.so.serviceinstancebeans.VfModules()
656                 vfModules.setModelInfo(vfModuleModelInfo)
657                 vfModules.setInstanceName(vfModuleModelInfo.getModelName())
658
659                 List<Map<String, Object>> vfModuleInstanceParams = new ArrayList<>()
660                 vfModules.setInstanceParams(vfModuleInstanceParams)
661                 vfModuless.add(vfModules)
662             }
663
664         } catch (Exception ex){
665             msg = "Exception in prepareVfModules " + ex.getMessage()
666             LOGGER.error(msg)
667             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
668         }
669
670         /*
671         List<org.onap.so.serviceinstancebeans.VfModules> vfModuless = new ArrayList<>()
672         if(constituteVnf.getVfModules() != null && constituteVnf.getVfModules().getVfModule() != null) {
673             for (VfModule vfModule : constituteVnf.getVfModules().getVfModule()) {
674                 org.onap.so.serviceinstancebeans.VfModules vfmodules = new org.onap.so.serviceinstancebeans.VfModules()
675
676                 ModelInfo vfModuleModelInfo = new ModelInfo()
677                 vfModuleModelInfo.setModelInvariantUuid(vfModule.getModelInvariantId())
678                 vfModuleModelInfo.setModelCustomizationId(vfModule.getModelCustomizationId())
679
680                 AAIResourceUri vfModuleUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(vfModule.getModelInvariantId()).modelVer(vfModule.getModelVersionId()))
681
682                 Optional<ModelVer> vfModuleModelVerOpt = client.get(ModelVer.class, vfModuleUrl)
683
684                 if (vfModuleModelVerOpt.isPresent()) {
685                     vfModuleModelInfo.setModelVersionId(vfModuleModelVerOpt.get().getModelVersionId())
686                     vfModuleModelInfo.setModelName(vfModuleModelVerOpt.get().getModelName())
687                     vfModuleModelInfo.setModelVersion(vfModuleModelVerOpt.get().getModelVersion())
688                 }
689                 vfmodules.setModelInfo(vfModuleModelInfo)
690
691                 vfmodules.setInstanceName(vfModule.getVfModuleName())
692
693                 vfModuless.add(vfmodules)
694             }
695         } */
696
697         LOGGER.debug("${getPrefix()} Exit prepareVfModules")
698
699         return vfModuless
700     }
701
702
703     /**
704      * prepares VNF Model Info
705      * @param execution
706      * @param constituteVnf
707      * @return ModelInfo
708      */
709     ModelInfo prepareVNFModelInfo(DelegateExecution execution, GenericVnf constituteVnf) {
710         LOGGER.debug("${getPrefix()} Start prepareVNFModelInfo")
711
712         ModelInfo vnfModelInfo = new ModelInfo()
713
714         AAIResourcesClient client = getAAIClient()
715
716         vnfModelInfo.setModelInvariantUuid(constituteVnf.getModelInvariantId())
717         vnfModelInfo.setModelCustomizationId(constituteVnf.getModelCustomizationId())
718         vnfModelInfo.setModelInstanceName(constituteVnf.getVnfName())
719
720         AAIResourceUri vnfModelUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(constituteVnf.getModelInvariantId()).modelVer(constituteVnf.getModelVersionId()))
721
722         Optional<ModelVer> vnfModelVerOpt = client.get(ModelVer.class, vnfModelUrl)
723
724         if (vnfModelVerOpt.isPresent()) {
725             vnfModelInfo.setModelVersionId(vnfModelVerOpt.get().getModelVersionId())
726             vnfModelInfo.setModelName(vnfModelVerOpt.get().getModelName())
727             vnfModelInfo.setModelVersion(vnfModelVerOpt.get().getModelVersion())
728         }
729
730         LOGGER.debug("${getPrefix()} Exit prepareVNFModelInfo")
731
732         return vnfModelInfo
733     }
734
735
736     List<Map<String, Object>> prepareInstanceParams(DelegateExecution execution) {
737         LOGGER.debug("${getPrefix()} Start prepareInstanceParams")
738
739         def currentNSSI = execution.getVariable("currentNSSI")
740
741         List<Map<String, Object>> instanceParams = new ArrayList<>()
742         Map<String, Object> instanceParamsMap = new HashMap<>()
743
744         // Supported S-NSSAI
745         def snssaisList = currentNSSI['S-NSSAIs']
746         List<String> snssais = new ArrayList<>()
747         if(snssaisList != null) {
748             snssais = new ArrayList<String>((List<String>)snssaisList)
749         }
750
751         LOGGER.debug("prepareInstanceParams: snssais size = " + snssais.size())
752
753         ServiceInstance nssi = (ServiceInstance) currentNSSI['nssi']
754
755         String orchStatus = nssi.getOrchestrationStatus()
756
757
758         List<Map<String, String>> snssaiList = new ArrayList<>()
759
760         for(String snssai:snssais) {
761             LOGGER.debug("prepareInstanceParams: snssai = " + snssai)
762             Map<String, String> snssaisMap = new HashMap<>()
763             snssaisMap.put("snssai", snssai)
764             snssaisMap.put("status", orchStatus)
765             snssaiList.add(snssaisMap)
766         }
767
768         //    Map<String, List<Map<String, String>>> supportedNssaiDetails = new HashMap<>()
769         //    supportedNssaiDetails.put("sNssai", supportedNssaiDetails)
770
771         ObjectMapper mapper = new ObjectMapper()
772
773         Map<String, Object> nSsai= new LinkedHashMap<>()
774         nSsai.put("sNssai", snssaiList)
775
776        // String supportedsNssaiJson = mapper.writeValueAsString(snssaiList)
777         String supportedsNssaiJson = mapper.writeValueAsString(nSsai)
778
779         instanceParamsMap.put("k8s-rb-profile-name", "default") // ???
780         instanceParamsMap.put("config-type", "day2") // ???
781         instanceParamsMap.put("supportedsNssai", supportedsNssaiJson)
782         instanceParams.add(instanceParamsMap)
783
784         LOGGER.debug("${getPrefix()} Exit prepareInstanceParams")
785
786         return instanceParams
787     }
788
789     /**
790      * Prepares Resources
791      * @param execution
792      * @return Resources
793      */
794     Resources prepareResources(DelegateExecution execution) {
795         LOGGER.debug("${getPrefix()} Start prepareResources")
796
797         def currentNSSI = execution.getVariable("currentNSSI")
798
799         Resources resources = new Resources()
800
801         // VNFs
802         List<Vnfs> vnfs = new ArrayList<>()
803         // VNF
804         Vnfs vnf = new Vnfs()
805
806         // Line of Business
807         org.onap.so.serviceinstancebeans.LineOfBusiness lob = new org.onap.so.serviceinstancebeans.LineOfBusiness()
808         lob.setLineOfBusinessName("VNF")
809         vnf.setLineOfBusiness(lob)
810
811         // Product family ID
812         GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
813         vnf.setProductFamilyId(constituteVnf.getServiceId())
814
815         // Cloud configuration
816         vnf.setCloudConfiguration(prepareCloudConfiguration(execution))
817
818         // VF Modules
819         vnf.setVfModules(prepareVfModules(execution, constituteVnf))
820
821         // Model Info
822         vnf.setModelInfo(prepareVNFModelInfo(execution, constituteVnf))
823
824         // Instance name
825         vnf.setInstanceName(constituteVnf.getVnfName())
826
827         // Instance params
828         vnf.setInstanceParams(prepareInstanceParams(execution))
829
830         // No platform data
831
832         vnfs.add(vnf)
833         resources.setVnfs(vnfs)
834
835         LOGGER.debug("${getPrefix()} Exit prepareResources")
836
837         return resources
838     }
839
840
841     /**
842      * Prepare Service
843      * @return Service
844      */
845     org.onap.so.serviceinstancebeans.Service prepareService(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
846         LOGGER.debug("${getPrefix()} Start prepareService")
847
848         org.onap.so.serviceinstancebeans.Service service = new org.onap.so.serviceinstancebeans.Service()
849
850         // Model Info
851         service.setModelInfo(prepareServiceModelInfo(networkServiceInstance, modelInfo))
852
853         service.setInstanceName(networkServiceInstance.getServiceInstanceName())
854
855         // Resources
856         service.setResources(prepareResources(execution))
857
858         LOGGER.debug("${getPrefix()} Exit prepareService")
859
860         return service
861
862     }
863
864
865     /**
866      * Prepares request parameters
867      * @param execution
868      * @return RequestParameters
869      */
870     RequestParameters prepareRequestParameters(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
871         LOGGER.debug("${getPrefix()} Start prepareRequestParameters")
872
873         def currentNSSI = execution.getVariable("currentNSSI")
874
875         RequestParameters requestParameters = new RequestParameters()
876
877         ServiceSubscription serviceSubscription = (ServiceSubscription)currentNSSI['serviceSubscription']
878
879         if(serviceSubscription != null) {
880             requestParameters.setSubscriptionServiceType(serviceSubscription.getServiceType())
881         }
882
883         // User params
884         List<Map<String, Object>> userParams = new ArrayList<>()
885
886         Map<String, Object> userParam = new HashMap<>()
887         userParam.put("Homing_Solution", "none")
888         userParams.add(userParam)
889
890         // Service
891         Map<String, Object> serviceMap = new HashMap<>()
892         serviceMap.put("service", prepareService(execution, networkServiceInstance, modelInfo))
893         userParams.add(serviceMap)
894         requestParameters.setUserParams(userParams)
895
896         requestParameters.setaLaCarte(false)
897
898         LOGGER.debug("${getPrefix()} Exit prepareRequestParameters")
899
900         return requestParameters
901     }
902
903
904     /**
905      * Prepare Owning Entity
906      * @param execution
907      * @return OwningEntity
908      */
909     org.onap.so.serviceinstancebeans.OwningEntity prepareOwningEntity(DelegateExecution execution) {
910         LOGGER.debug("${getPrefix()} Start prepareOwningEntity")
911
912         def currentNSSI = execution.getVariable("currentNSSI")
913
914         AAIResourcesClient client = getAAIClient()
915
916         AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
917
918         org.onap.so.serviceinstancebeans.OwningEntity owningEntity = new org.onap.so.serviceinstancebeans.OwningEntity()
919         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
920         Optional<Relationships> owningEntityRelationshipsOps = wrapper.getRelationships()
921         if (owningEntityRelationshipsOps.isPresent()) {
922             List<AAIResourceUri> owningEntityRelatedAAIUris = owningEntityRelationshipsOps.get().getRelatedUris(Types.OWNING_ENTITY)
923
924             if (!(owningEntityRelatedAAIUris == null || owningEntityRelatedAAIUris.isEmpty())) {
925                 Optional<org.onap.aai.domain.yang.OwningEntity> owningEntityOpt = client.get(org.onap.aai.domain.yang.v19.OwningEntity.class, owningEntityRelatedAAIUris.get(0)) // Many-To-One relation
926                 if (owningEntityOpt.isPresent()) {
927                     owningEntity.setOwningEntityId(owningEntityOpt.get().getOwningEntityId())
928                     owningEntity.setOwningEntityName(owningEntityOpt.get().getOwningEntityName())
929
930                 }
931             }
932         }
933
934         LOGGER.debug("${getPrefix()} Exit prepareOwningEntity")
935
936         return owningEntity
937     }
938
939
940     /**
941      * Prepares Project
942      * @param execution
943      * @return Project
944      */
945     org.onap.so.serviceinstancebeans.Project prepareProject(DelegateExecution execution) {
946         LOGGER.debug("${getPrefix()} Start prepareProject")
947
948         def currentNSSI = execution.getVariable("currentNSSI")
949
950         AAIResourcesClient client = getAAIClient()
951
952         org.onap.so.serviceinstancebeans.Project project = new org.onap.so.serviceinstancebeans.Project()
953
954         AAIResourceUri cloudRegionRelatedAAIUri = (AAIResourceUri)currentNSSI['cloudRegionRelatedAAIUri']
955
956         if (cloudRegionRelatedAAIUri != null) {
957             AAIResultWrapper wrapper = client.get(cloudRegionRelatedAAIUri)
958             Optional<Relationships> cloudRegionOps = wrapper.getRelationships()
959             if (cloudRegionOps.isPresent()) {
960                 List<AAIResourceUri> projectAAIUris = cloudRegionOps.get().getRelatedUris(Types.PROJECT)
961                 if (!(projectAAIUris == null || projectAAIUris.isEmpty())) {
962                     Optional<org.onap.aai.domain.yang.Project> projectOpt = client.get(org.onap.aai.domain.yang.v19.Project.class, projectAAIUris.get(0))
963                     if (projectOpt.isPresent()) {
964                         project.setProjectName(projectOpt.get().getProjectName())
965                     }
966                 }
967             }
968         }
969
970         LOGGER.debug("${getPrefix()} Exit prepareProject")
971
972         return project
973     }
974
975
976     /**
977      * Prepares RequestDetails object
978      * @param execution
979      * @return
980      */
981     String prepareRequestDetails(DelegateExecution execution) {
982         LOGGER.debug("${getPrefix()} Start prepareRequestDetails")
983
984         String errorCode = ""
985         String errorMessage = ""
986         String response
987
988         RequestDetails requestDetails = new RequestDetails()
989
990         def currentNSSI = execution.getVariable("currentNSSI")
991
992         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
993
994         try {
995             // Model Info
996             ModelInfo modelInfo = prepareModelInfo(execution)
997             requestDetails.setModelInfo(modelInfo)
998
999             // Subscriber Info
1000             requestDetails.setSubscriberInfo(prepareSubscriberInfo(execution))
1001
1002             // Request Info
1003             requestDetails.setRequestInfo(prepareRequestInfo(execution, networkServiceInstance))
1004
1005             // Request Parameters
1006             requestDetails.setRequestParameters(prepareRequestParameters(execution, networkServiceInstance, modelInfo))
1007
1008             // Cloud configuration
1009             requestDetails.setCloudConfiguration(prepareCloudConfiguration(execution))
1010
1011             // Owning entity
1012             requestDetails.setOwningEntity(prepareOwningEntity(execution))
1013
1014             // Project
1015             requestDetails.setProject(prepareProject(execution))
1016
1017             Map<String, Object> requestDetailsMap = new LinkedHashMap<>()
1018             requestDetailsMap.put("requestDetails", requestDetails)
1019
1020             ObjectMapper mapper = new ObjectMapper()
1021
1022             response = mapper.writeValueAsString(requestDetailsMap)
1023         }
1024         catch (any) {
1025             String msg = "Exception in ${getPrefix()}.prepareRequestDetails. " + any.getCause()
1026             LOGGER.error(msg)
1027
1028             response =  "{\n" +
1029                     " \"errorCode\": \"7000\",\n" +
1030                     " \"errorMessage\": \"${msg}\"\n" +
1031                     "}"
1032
1033         }
1034
1035         LOGGER.debug("${getPrefix()} Exit prepareRequestDetails")
1036
1037         return response
1038     }
1039
1040
1041     String getAuthHeader(DelegateExecution execution, String basicAuthValue, String msokey) {
1042         String response = ""
1043         String errorCode = ""
1044         String errorMessage = ""
1045
1046         LOGGER.debug("Obtained BasicAuth username and password for OOF: " + basicAuthValue)
1047         try {
1048             response = utils.getBasicAuth(basicAuthValue, msokey)
1049         } catch (Exception ex) {
1050             LOGGER.error("Unable to encode username and password string: ", ex)
1051
1052             errorCode = "401"
1053             errorMessage = "Internal Error - Unable to encode username and password string"
1054
1055             response =  "{\n" +
1056                     " \"errorCode\": \"${errorCode}\",\n" +
1057                     " \"errorMessage\": \"${errorMessage}\"\n" +
1058                     "}"
1059         }
1060
1061         return response
1062     }
1063
1064
1065     String encryptBasicAuth(String basicAuth, String msoKey) {
1066         return utils.encrypt(basicAuth, msoKey)
1067     }
1068
1069
1070     /**
1071      * Retrieves NSSI associated profiles from AAI
1072      * @param execution
1073      */
1074     void getNSSIAssociatedProfiles(DelegateExecution execution) {
1075         LOGGER.debug("${getPrefix()} Start getNSSIAssociatedProfiles")
1076
1077         List<SliceProfile> associatedProfiles = new ArrayList<>()
1078
1079         AAIResourcesClient client = getAAIClient()
1080
1081         def currentNSSI = execution.getVariable("currentNSSI")
1082
1083         ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
1084
1085         String nssiId = currentNSSI['nssiId']
1086
1087         String givenSliceProfileId = currentNSSI['sliceProfileId']
1088
1089         // NSSI
1090         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
1091         AAIResultWrapper nssiWrapper = client.get(nssiUri)
1092         Optional<Relationships> nssiRelationships = nssiWrapper.getRelationships()
1093
1094         if (nssiRelationships.isPresent()) {
1095             // Allotted Resource
1096             for (AAIResourceUri allottedResourceUri : nssiRelationships.get().getRelatedUris(Types.ALLOTTED_RESOURCE)) {
1097                 AAIResultWrapper arWrapper = client.get(allottedResourceUri)
1098                 Optional<Relationships> arRelationships = arWrapper.getRelationships()
1099
1100                 if(arRelationships.isPresent()) {
1101                     // Slice Profile Instance
1102                     for (AAIResourceUri sliceProfileInstanceUri : arRelationships.get().getRelatedUris(Types.SERVICE_INSTANCE)) {
1103                         Optional<ServiceInstance> sliceProfileInstanceOpt = client.get(ServiceInstance.class, sliceProfileInstanceUri)
1104
1105                         if (sliceProfileInstanceOpt.isPresent()) {
1106                             ServiceInstance sliceProfileInstance = sliceProfileInstanceOpt.get()
1107                             if(sliceProfileInstance.getServiceRole().equals("slice-profile-instance")) { // Service instance as a Slice Profile Instance
1108
1109                                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
1110                                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
1111
1112                                 org.onap.aaiclient.client.generated.fluentbuilders.SliceProfiles sliceProfilesType =
1113                                         AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(sliceProfileInstance.getServiceInstanceId()).sliceProfiles()
1114
1115                                 def sliceProfilesUri = AAIUriFactory.createResourceUri(sliceProfilesType)
1116                                 LOGGER.debug("client.exists(sliceProfilesUri = " + client.exists(sliceProfilesUri))
1117                                 if (!client.exists(sliceProfilesUri)) {
1118                                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Slice Profiles URI doesn't exist")
1119                                 }
1120
1121                                 AAIResultWrapper sliceProfilesWrapper = client.get(sliceProfilesUri)
1122                                 Optional<SliceProfiles> sliceProfilesOpt = sliceProfilesWrapper.asBean(SliceProfiles.class)
1123                                 if(sliceProfilesOpt.isPresent()) {
1124                                     SliceProfiles sliceProfiles = sliceProfilesOpt.get()
1125
1126                                     LOGGER.debug("getNSSIAssociatedProfiles: sliceProfiles.getSliceProfile().size() = " + sliceProfiles.getSliceProfile().size())
1127                                     LOGGER.debug("getNSSIAssociatedProfiles: givenSliceProfileId = " + givenSliceProfileId)
1128                                     for(SliceProfile sliceProfile: sliceProfiles.getSliceProfile()) {
1129                                         LOGGER.debug("getNSSIAssociatedProfiles: sliceProfile.getProfileId() = " + sliceProfile.getProfileId())
1130                                         if(sliceProfile.getProfileId().equals(givenSliceProfileId)) { // Slice profile id equals to received slice profile id
1131                                             currentNSSI['sliceProfileInstanceUri'] = sliceProfileInstanceUri
1132                                         }
1133
1134                                     }
1135
1136                                     associatedProfiles.addAll(sliceProfiles.getSliceProfile()) // Adds all slice profiles
1137                                 }
1138
1139                             }
1140                         }
1141                         else {
1142                             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No Slice Profile Instance found")
1143                         }
1144                     }
1145                 }
1146                 else {
1147                     exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No relationships found for Allotted Resource")
1148                 }
1149
1150             }
1151         }
1152         else {
1153             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No relationships  found for nssi id = " + nssiId)
1154         }
1155
1156         checkAssociatedProfiles(execution, associatedProfiles, nssi)
1157
1158         currentNSSI['associatedProfiles'] =  associatedProfiles
1159
1160         LOGGER.debug("${getPrefix()} Exit getNSSIAssociatedProfiles")
1161     }
1162
1163
1164     void checkAssociatedProfiles(DelegateExecution execution, List<SliceProfile> associatedProfiles, ServiceInstance nssi) {}
1165
1166
1167     /**
1168      * Removes Slice Profile association with NSSI
1169      * @param execution
1170      */
1171     void removeSPAssociationWithNSSI(DelegateExecution execution) {
1172         LOGGER.debug("${getPrefix()} Start removeSPAssociationWithNSSI")
1173
1174         AAIResourcesClient client = getAAIClient()
1175
1176         def currentNSSI = execution.getVariable("currentNSSI")
1177
1178         String nssiId = currentNSSI['nssiId']
1179         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
1180
1181         String isTerminateNSSIVar = execution.getVariable("isTerminateNSSI" )
1182
1183         boolean isTerminateNSSI = Boolean.parseBoolean(isTerminateNSSIVar)
1184
1185         AAIResourceUri sliceProfileInstanceUri = null
1186         if(!isTerminateNSSI) { // In case of NSSI non-termination associated Slice Profile Instance should be presented
1187             def spURI = currentNSSI['sliceProfileInstanceUri']
1188             if(spURI != null) {
1189                 sliceProfileInstanceUri = (AAIResourceUri)spURI
1190             }
1191             else {
1192                 String msg = "Slice Profile association with NSSI was already removed"
1193                 LOGGER.info(msg)
1194             }
1195         }
1196
1197         // Removes SLice Profile Instance association with NSSI
1198         if(sliceProfileInstanceUri != null) { // NSSI should not be terminated
1199             try {
1200                 client.disconnect(nssiUri, sliceProfileInstanceUri)
1201             }
1202             catch (Exception e) {
1203                 exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance association with NSSI dosconnect call: " + e.getMessage())
1204             }
1205         }
1206
1207
1208         LOGGER.debug("${getPrefix()} Exit removeSPAssociationWithNSSI")
1209     }
1210
1211
1212     /**
1213      * Deletes Slice Profile Instance
1214      * @param execution
1215      */
1216     void deleteSliceProfileInstance(DelegateExecution execution) {
1217         LOGGER.debug("${getPrefix()} Start deleteSliceProfileInstance")
1218
1219         AAIResourcesClient client = getAAIClient()
1220
1221         def currentNSSI = execution.getVariable("currentNSSI")
1222
1223         String isTerminateNSSIVar = execution.getVariable("isTerminateNSSI" )
1224
1225         boolean isTerminateNSSI = Boolean.parseBoolean(isTerminateNSSIVar)
1226
1227         AAIResourceUri sliceProfileInstanceUri = null
1228         if(!isTerminateNSSI) { // In case of NSSI non-termination associated Slice Profile Instance should be presented
1229             def spURI = currentNSSI['sliceProfileInstanceUri']
1230             if(spURI != null) {
1231                 sliceProfileInstanceUri = (AAIResourceUri)spURI
1232             }
1233             else {
1234                 String msg = "Slice Profile instance was already deleted"
1235                 LOGGER.info(msg)
1236             }
1237         }
1238
1239         if(sliceProfileInstanceUri != null) {
1240             try {
1241                 client.delete(sliceProfileInstanceUri)
1242             } catch (Exception e) {
1243                 exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance delete call: " + e.getMessage())
1244             }
1245         }
1246
1247         LOGGER.debug("${getPrefix()} Exit deleteSliceProfileInstance")
1248     }
1249
1250
1251     /**
1252      * Prepares update resource operation status
1253      * @param execution
1254      */
1255     void prepareUpdateResourceOperationStatus(DelegateExecution execution) {
1256         LOGGER.debug("${getPrefix()} Start updateServiceOperationStatus")
1257
1258         def currentNSSI = execution.getVariable("currentNSSI")
1259
1260         //Prepare Update Status for PUT failure and success
1261         String isTimeOutVar = execution.getVariable("isTimeOut")
1262         if(!isBlank(isTimeOutVar) && isTimeOutVar.equals("YES")) {
1263             LOGGER.error("TIMEOUT - SO PUT Failure")
1264             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "SO PUT Failure")
1265         } else {
1266             execution.setVariable("progress", "100")
1267             execution.setVariable("status", "finished")
1268             execution.setVariable("operationContent", "${getAction()} Core NSSI successful.")
1269         }
1270
1271         setResourceOperationStatus(execution, "finished", "100", "Core NSSI ${getAction()} successful")
1272
1273         LOGGER.debug("${getPrefix()} Exit updateServiceOperationStatus")
1274     }
1275
1276
1277     /**
1278      * Prepares ResourceOperation status
1279      * @param execution
1280      * @param operationType
1281      */
1282     void setResourceOperationStatus(DelegateExecution execution, String status, String progress, String statusDesc) {
1283         LOGGER.debug("${getPrefix()} Start setResourceOperationStatus")
1284
1285         def currentNSSI = execution.getVariable("currentNSSI")
1286
1287         String serviceId = currentNSSI['nsiId']
1288         String jobId = execution.getVariable("jobId")
1289         String nsiId = currentNSSI['nsiId']
1290         String operationType = execution.getVariable("operationType")
1291         String resourceInstanceId = currentNSSI['nssiId']
1292
1293         ServiceInstance nssi = (ServiceInstance) currentNSSI['nssi']
1294         String modelUuid = nssi.getModelVersionId()
1295
1296         ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
1297         resourceOperationStatus.setServiceId(serviceId)
1298         resourceOperationStatus.setOperationId(jobId)
1299         resourceOperationStatus.setResourceTemplateUUID(modelUuid)
1300         resourceOperationStatus.setOperType(operationType)
1301         resourceOperationStatus.setResourceInstanceID(resourceInstanceId)
1302         resourceOperationStatus.setStatus(status)
1303         resourceOperationStatus.setProgress(progress)
1304         resourceOperationStatus.setStatusDescription(statusDesc)
1305         requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
1306
1307         LOGGER.debug("${getPrefix()} Exit setResourceOperationStatus")
1308     }
1309
1310
1311     /**
1312      * Prepares failed operation status update
1313      * @param execution
1314      */
1315     void prepareFailedOperationStatusUpdate(DelegateExecution execution) {
1316         LOGGER.debug("${getPrefix()} Start prepareFailedOperationStatusUpdate")
1317
1318         setResourceOperationStatus(execution, "failed", "0", "Core NSSI ${getAction()} Failed")
1319
1320         LOGGER.debug("${getPrefix()} Exit prepareFailedOperationStatusUpdate")
1321     }
1322
1323
1324     /**
1325      * Gets progress status of ServiceInstance PUT operation
1326      * @param execution
1327      */
1328     public void getPUTServiceInstanceProgress(DelegateExecution execution) {
1329         LOGGER.debug("${getPrefix()} Start getPUTServiceInstanceProgress")
1330
1331         def currentNSSI = execution.getVariable("currentNSSI")
1332
1333         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
1334
1335         String url = currentNSSI['requestSelfLink']
1336
1337         String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
1338
1339         String basicAuth =  UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution)
1340
1341         def authHeader = ""
1342         String basicAuthValue = utils.getBasicAuth(basicAuth, msoKey)
1343
1344         getProgress(execution, url, basicAuthValue, "putStatus")
1345
1346         LOGGER.debug("${getPrefix()} Exit getPUTServiceInstanceProgress")
1347     }
1348
1349
1350     void getProgress(DelegateExecution execution, String url, String authHeader, String statusVariableName) {
1351         LOGGER.debug("${getPrefix()} Start getProgress")
1352
1353         LOGGER.debug("getProgress: url = " + url)
1354         LOGGER.debug("getProgress: authHeader = " + authHeader)
1355
1356         String msg=""
1357         try {
1358
1359             HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.SO)
1360             httpClient.addAdditionalHeader("Authorization", authHeader)
1361             httpClient.addAdditionalHeader("Accept", "application/json")
1362
1363             Response response = httpClient.get()
1364             int responseCode = response.getStatus()
1365           //  execution.setVariable("GetServiceOrderResponseCode", responseCode)
1366             LOGGER.debug("Get ServiceOrder response code is: " + responseCode)
1367
1368             String soResponse = ""
1369             if(response.hasEntity()) {
1370                 soResponse = response.readEntity(String.class)
1371          //       execution.setVariable("GetServiceOrderResponse", extApiResponse)
1372                 LOGGER.debug("Create response body is: " + soResponse)
1373             }
1374
1375             //Process Response //200 OK 201 CREATED 202 ACCEPTED
1376             if (responseCode >= 200 && responseCode < 204) {
1377                 LOGGER.debug("Get Create ServiceOrder Received a Good Response")
1378                 String requestState = jsonUtil.getJsonValue(soResponse, "request.requestStatus.requestState")
1379
1380                 /*
1381                 JSONArray items = responseObj.getJSONArray("orderItem")
1382                 JSONObject item = items.get(0)
1383                 JSONObject service = item.get("service")
1384                 String networkServiceId = service.get("id")
1385                 if (networkServiceId == null || networkServiceId.equals("null")) {
1386                     prepareFailedOperationStatusUpdate(execution)
1387                     return
1388                 }
1389
1390                 execution.setVariable("networkServiceId", networkServiceId)
1391                 String serviceOrderState = item.get("state")
1392                 execution.setVariable("ServiceOrderState", serviceOrderState) */
1393
1394                 // Get serviceOrder State and process progress
1395                 if("ACKNOWLEDGED".equalsIgnoreCase(requestState)) {
1396                     execution.setVariable(statusVariableName, "processing")
1397                 }
1398                 else if("IN_PROGRESS".equalsIgnoreCase(requestState)) {
1399                     execution.setVariable(statusVariableName, "processing")
1400                 }
1401                 else if("COMPLETE".equalsIgnoreCase(requestState)) {
1402                     execution.setVariable(statusVariableName, "completed")
1403                 }
1404                 else if("FAILED".equalsIgnoreCase(requestState)) {
1405                     msg = "ServiceOrder failed"
1406                     exceptionUtil.buildAndThrowWorkflowException(execution, 7000,  msg)
1407                 }
1408                 else if("REJECTED".equalsIgnoreCase(requestState)) {
1409                     prepareFailedOperationStatusUpdate(execution)
1410                 }
1411                 else {
1412                     msg = "ServiceOrder failed"
1413                     exceptionUtil.buildAndThrowWorkflowException(execution, 7000,  msg)
1414                 }
1415             }
1416             else{
1417                 msg = "Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode
1418                 prepareFailedOperationStatusUpdate(execution)
1419             }
1420
1421         }catch(Exception e){
1422             exceptionUtil.buildAndThrowWorkflowException(execution, 7000,  e.getMessage())
1423         }
1424
1425         LOGGER.debug("${getPrefix()} Exit getProgress")
1426     }
1427
1428
1429
1430     /**
1431      * Delays 5 sec
1432      * @param execution
1433      */
1434     void timeDelay(DelegateExecution execution) {
1435         LOGGER.debug("${getPrefix()} Start timeDelay")
1436
1437         try {
1438             LOGGER.debug("${getPrefix()} timeDelay going to sleep for 5 sec")
1439
1440             Thread.sleep(5000)
1441
1442             LOGGER.debug("${getPrefix()} ::: timeDelay wakeup after 5 sec")
1443         } catch(InterruptedException e) {
1444             LOGGER.error("${getPrefix()} ::: timeDelay exception" + e)
1445         }
1446
1447         LOGGER.debug("${getPrefix()} Exit timeDelay")
1448     }
1449
1450
1451     void postProcessRequest(DelegateExecution execution) {
1452         LOGGER.debug("${getPrefix()} Start postProcessRequest")
1453
1454         execution.removeVariable("currentNSSI")
1455
1456         LOGGER.debug("***** ${getPrefix()} Exit postProcessRequest")
1457     }
1458
1459
1460
1461     /**
1462      * Returns AAI client
1463      * @return AAI client
1464      */
1465     AAIResourcesClient getAAIClient() {
1466         return new AAIResourcesClient()
1467     }
1468
1469
1470     ExternalAPIUtilFactory getExternalAPIUtilFactory() {
1471         return new ExternalAPIUtilFactory()
1472     }
1473
1474
1475     /**
1476      * Returns Catalog DB Util Factory
1477      * @return ew CatalogDbUtilsFactory()
1478      */
1479     CatalogDbUtilsFactory getCatalogDbUtilsFactory() {
1480         return new CatalogDbUtilsFactory()
1481     }
1482
1483
1484     private String getPrefix() {
1485         return PREFIX
1486     }
1487
1488     String getAction() {
1489         return ""
1490     }
1491 }