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