Wrong additional parameter for OOF's terminateNxiRequest
[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         List<String> snssais = (List<String>) currentNSSI['S-NSSAIs']
746
747         LOGGER.debug("prepareInstanceParams: snssais size = " + snssais.size())
748
749         ServiceInstance nssi = (ServiceInstance) currentNSSI['nssi']
750
751         String orchStatus = nssi.getOrchestrationStatus()
752
753
754         List<Map<String, String>> snssaiList = new ArrayList<>()
755
756         for(String snssai:snssais) {
757             LOGGER.debug("prepareInstanceParams: snssai = " + snssai)
758             Map<String, String> snssaisMap = new HashMap<>()
759             snssaisMap.put("snssai", snssai)
760             snssaisMap.put("status", orchStatus)
761             snssaiList.add(snssaisMap)
762         }
763
764         //    Map<String, List<Map<String, String>>> supportedNssaiDetails = new HashMap<>()
765         //    supportedNssaiDetails.put("sNssai", supportedNssaiDetails)
766
767         ObjectMapper mapper = new ObjectMapper()
768
769         Map<String, Object> nSsai= new LinkedHashMap<>()
770         nSsai.put("sNssai", snssaiList)
771
772        // String supportedsNssaiJson = mapper.writeValueAsString(snssaiList)
773         String supportedsNssaiJson = mapper.writeValueAsString(nSsai)
774
775         instanceParamsMap.put("k8s-rb-profile-name", "default") // ???
776         instanceParamsMap.put("config-type", "day2") // ???
777         instanceParamsMap.put("supportedsNssai", supportedsNssaiJson)
778         instanceParams.add(instanceParamsMap)
779
780         LOGGER.debug("${getPrefix()} Exit prepareInstanceParams")
781
782         return instanceParams
783     }
784
785     /**
786      * Prepares Resources
787      * @param execution
788      * @return Resources
789      */
790     Resources prepareResources(DelegateExecution execution) {
791         LOGGER.debug("${getPrefix()} Start prepareResources")
792
793         def currentNSSI = execution.getVariable("currentNSSI")
794
795         Resources resources = new Resources()
796
797         // VNFs
798         List<Vnfs> vnfs = new ArrayList<>()
799         // VNF
800         Vnfs vnf = new Vnfs()
801
802         // Line of Business
803         org.onap.so.serviceinstancebeans.LineOfBusiness lob = new org.onap.so.serviceinstancebeans.LineOfBusiness()
804         lob.setLineOfBusinessName("VNF")
805         vnf.setLineOfBusiness(lob)
806
807         // Product family ID
808         GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
809         vnf.setProductFamilyId(constituteVnf.getServiceId())
810
811         // Cloud configuration
812         vnf.setCloudConfiguration(prepareCloudConfiguration(execution))
813
814         // VF Modules
815         vnf.setVfModules(prepareVfModules(execution, constituteVnf))
816
817         // Model Info
818         vnf.setModelInfo(prepareVNFModelInfo(execution, constituteVnf))
819
820         // Instance name
821         vnf.setInstanceName(constituteVnf.getVnfName())
822
823         // Instance params
824         vnf.setInstanceParams(prepareInstanceParams(execution))
825
826         // No platform data
827
828         vnfs.add(vnf)
829         resources.setVnfs(vnfs)
830
831         LOGGER.debug("${getPrefix()} Exit prepareResources")
832
833         return resources
834     }
835
836
837     /**
838      * Prepare Service
839      * @return Service
840      */
841     org.onap.so.serviceinstancebeans.Service prepareService(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
842         LOGGER.debug("${getPrefix()} Start prepareService")
843
844         org.onap.so.serviceinstancebeans.Service service = new org.onap.so.serviceinstancebeans.Service()
845
846         // Model Info
847         service.setModelInfo(prepareServiceModelInfo(networkServiceInstance, modelInfo))
848
849         service.setInstanceName(networkServiceInstance.getServiceInstanceName())
850
851         // Resources
852         service.setResources(prepareResources(execution))
853
854         LOGGER.debug("${getPrefix()} Exit prepareService")
855
856         return service
857
858     }
859
860
861     /**
862      * Prepares request parameters
863      * @param execution
864      * @return RequestParameters
865      */
866     RequestParameters prepareRequestParameters(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
867         LOGGER.debug("${getPrefix()} Start prepareRequestParameters")
868
869         def currentNSSI = execution.getVariable("currentNSSI")
870
871         RequestParameters requestParameters = new RequestParameters()
872
873         ServiceSubscription serviceSubscription = (ServiceSubscription)currentNSSI['serviceSubscription']
874
875         if(serviceSubscription != null) {
876             requestParameters.setSubscriptionServiceType(serviceSubscription.getServiceType())
877         }
878
879         // User params
880         List<Map<String, Object>> userParams = new ArrayList<>()
881
882         Map<String, Object> userParam = new HashMap<>()
883         userParam.put("Homing_Solution", "none")
884         userParams.add(userParam)
885
886         // Service
887         Map<String, Object> serviceMap = new HashMap<>()
888         serviceMap.put("service", prepareService(execution, networkServiceInstance, modelInfo))
889         userParams.add(serviceMap)
890         requestParameters.setUserParams(userParams)
891
892         requestParameters.setaLaCarte(false)
893
894         LOGGER.debug("${getPrefix()} Exit prepareRequestParameters")
895
896         return requestParameters
897     }
898
899
900     /**
901      * Prepare Owning Entity
902      * @param execution
903      * @return OwningEntity
904      */
905     org.onap.so.serviceinstancebeans.OwningEntity prepareOwningEntity(DelegateExecution execution) {
906         LOGGER.debug("${getPrefix()} Start prepareOwningEntity")
907
908         def currentNSSI = execution.getVariable("currentNSSI")
909
910         AAIResourcesClient client = getAAIClient()
911
912         AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
913
914         org.onap.so.serviceinstancebeans.OwningEntity owningEntity = new org.onap.so.serviceinstancebeans.OwningEntity()
915         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
916         Optional<Relationships> owningEntityRelationshipsOps = wrapper.getRelationships()
917         if (owningEntityRelationshipsOps.isPresent()) {
918             List<AAIResourceUri> owningEntityRelatedAAIUris = owningEntityRelationshipsOps.get().getRelatedUris(Types.OWNING_ENTITY)
919
920             if (!(owningEntityRelatedAAIUris == null || owningEntityRelatedAAIUris.isEmpty())) {
921                 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
922                 if (owningEntityOpt.isPresent()) {
923                     owningEntity.setOwningEntityId(owningEntityOpt.get().getOwningEntityId())
924                     owningEntity.setOwningEntityName(owningEntityOpt.get().getOwningEntityName())
925
926                 }
927             }
928         }
929
930         LOGGER.debug("${getPrefix()} Exit prepareOwningEntity")
931
932         return owningEntity
933     }
934
935
936     /**
937      * Prepares Project
938      * @param execution
939      * @return Project
940      */
941     org.onap.so.serviceinstancebeans.Project prepareProject(DelegateExecution execution) {
942         LOGGER.debug("${getPrefix()} Start prepareProject")
943
944         def currentNSSI = execution.getVariable("currentNSSI")
945
946         AAIResourcesClient client = getAAIClient()
947
948         org.onap.so.serviceinstancebeans.Project project = new org.onap.so.serviceinstancebeans.Project()
949
950         AAIResourceUri cloudRegionRelatedAAIUri = (AAIResourceUri)currentNSSI['cloudRegionRelatedAAIUri']
951
952         if (cloudRegionRelatedAAIUri != null) {
953             AAIResultWrapper wrapper = client.get(cloudRegionRelatedAAIUri)
954             Optional<Relationships> cloudRegionOps = wrapper.getRelationships()
955             if (cloudRegionOps.isPresent()) {
956                 List<AAIResourceUri> projectAAIUris = cloudRegionOps.get().getRelatedUris(Types.PROJECT)
957                 if (!(projectAAIUris == null || projectAAIUris.isEmpty())) {
958                     Optional<org.onap.aai.domain.yang.Project> projectOpt = client.get(org.onap.aai.domain.yang.v19.Project.class, projectAAIUris.get(0))
959                     if (projectOpt.isPresent()) {
960                         project.setProjectName(projectOpt.get().getProjectName())
961                     }
962                 }
963             }
964         }
965
966         LOGGER.debug("${getPrefix()} Exit prepareProject")
967
968         return project
969     }
970
971
972     /**
973      * Prepares RequestDetails object
974      * @param execution
975      * @return
976      */
977     String prepareRequestDetails(DelegateExecution execution) {
978         LOGGER.debug("${getPrefix()} Start prepareRequestDetails")
979
980         String errorCode = ""
981         String errorMessage = ""
982         String response
983
984         RequestDetails requestDetails = new RequestDetails()
985
986         def currentNSSI = execution.getVariable("currentNSSI")
987
988         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
989
990         try {
991             // Model Info
992             ModelInfo modelInfo = prepareModelInfo(execution)
993             requestDetails.setModelInfo(modelInfo)
994
995             // Subscriber Info
996             requestDetails.setSubscriberInfo(prepareSubscriberInfo(execution))
997
998             // Request Info
999             requestDetails.setRequestInfo(prepareRequestInfo(execution, networkServiceInstance))
1000
1001             // Request Parameters
1002             requestDetails.setRequestParameters(prepareRequestParameters(execution, networkServiceInstance, modelInfo))
1003
1004             // Cloud configuration
1005             requestDetails.setCloudConfiguration(prepareCloudConfiguration(execution))
1006
1007             // Owning entity
1008             requestDetails.setOwningEntity(prepareOwningEntity(execution))
1009
1010             // Project
1011             requestDetails.setProject(prepareProject(execution))
1012
1013             Map<String, Object> requestDetailsMap = new LinkedHashMap<>()
1014             requestDetailsMap.put("requestDetails", requestDetails)
1015
1016             ObjectMapper mapper = new ObjectMapper()
1017
1018             response = mapper.writeValueAsString(requestDetailsMap)
1019         }
1020         catch (any) {
1021             String msg = "Exception in ${getPrefix()}.prepareRequestDetails. " + any.getCause()
1022             LOGGER.error(msg)
1023
1024             response =  "{\n" +
1025                     " \"errorCode\": \"7000\",\n" +
1026                     " \"errorMessage\": \"${msg}\"\n" +
1027                     "}"
1028
1029         }
1030
1031         LOGGER.debug("${getPrefix()} Exit prepareRequestDetails")
1032
1033         return response
1034     }
1035
1036
1037     String getAuthHeader(DelegateExecution execution, String basicAuthValue, String msokey) {
1038         String response = ""
1039         String errorCode = ""
1040         String errorMessage = ""
1041
1042         LOGGER.debug("Obtained BasicAuth username and password for OOF: " + basicAuthValue)
1043         try {
1044             response = utils.getBasicAuth(basicAuthValue, msokey)
1045         } catch (Exception ex) {
1046             LOGGER.error("Unable to encode username and password string: ", ex)
1047
1048             errorCode = "401"
1049             errorMessage = "Internal Error - Unable to encode username and password string"
1050
1051             response =  "{\n" +
1052                     " \"errorCode\": \"${errorCode}\",\n" +
1053                     " \"errorMessage\": \"${errorMessage}\"\n" +
1054                     "}"
1055         }
1056
1057         return response
1058     }
1059
1060
1061     String encryptBasicAuth(String basicAuth, String msoKey) {
1062         return utils.encrypt(basicAuth, msoKey)
1063     }
1064
1065
1066     /**
1067      * Retrieves NSSI associated profiles from AAI
1068      * @param execution
1069      */
1070     void getNSSIAssociatedProfiles(DelegateExecution execution) {
1071         LOGGER.debug("${getPrefix()} Start getNSSIAssociatedProfiles")
1072
1073         List<SliceProfile> associatedProfiles = new ArrayList<>()
1074
1075         AAIResourcesClient client = getAAIClient()
1076
1077         def currentNSSI = execution.getVariable("currentNSSI")
1078
1079         ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
1080
1081         String nssiId = currentNSSI['nssiId']
1082
1083         String givenSliceProfileId = currentNSSI['sliceProfileId']
1084
1085         // NSSI
1086         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
1087         AAIResultWrapper nssiWrapper = client.get(nssiUri)
1088         Optional<Relationships> nssiRelationships = nssiWrapper.getRelationships()
1089
1090         if (nssiRelationships.isPresent()) {
1091             // Allotted Resource
1092             for (AAIResourceUri allottedResourceUri : nssiRelationships.get().getRelatedUris(Types.ALLOTTED_RESOURCE)) {
1093                 AAIResultWrapper arWrapper = client.get(allottedResourceUri)
1094                 Optional<Relationships> arRelationships = arWrapper.getRelationships()
1095
1096                 if(arRelationships.isPresent()) {
1097                     // Slice Profile Instance
1098                     for (AAIResourceUri sliceProfileInstanceUri : arRelationships.get().getRelatedUris(Types.SERVICE_INSTANCE)) {
1099                         Optional<ServiceInstance> sliceProfileInstanceOpt = client.get(ServiceInstance.class, sliceProfileInstanceUri)
1100
1101                         if (sliceProfileInstanceOpt.isPresent()) {
1102                             ServiceInstance sliceProfileInstance = sliceProfileInstanceOpt.get()
1103                             if(sliceProfileInstance.getServiceRole().equals("slice-profile-instance")) { // Service instance as a Slice Profile Instance
1104
1105                                 String globalSubscriberId = execution.getVariable("globalSubscriberId")
1106                                 String subscriptionServiceType = execution.getVariable("subscriptionServiceType")
1107
1108                                 org.onap.aaiclient.client.generated.fluentbuilders.SliceProfiles sliceProfilesType =
1109                                         AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(subscriptionServiceType).serviceInstance(sliceProfileInstance.getServiceInstanceId()).sliceProfiles()
1110
1111                                 def sliceProfilesUri = AAIUriFactory.createResourceUri(sliceProfilesType)
1112                                 LOGGER.debug("client.exists(sliceProfilesUri = " + client.exists(sliceProfilesUri))
1113                                 if (!client.exists(sliceProfilesUri)) {
1114                                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Slice Profiles URI doesn't exist")
1115                                 }
1116
1117                                 AAIResultWrapper sliceProfilesWrapper = client.get(sliceProfilesUri)
1118                                 Optional<SliceProfiles> sliceProfilesOpt = sliceProfilesWrapper.asBean(SliceProfiles.class)
1119                                 if(sliceProfilesOpt.isPresent()) {
1120                                     SliceProfiles sliceProfiles = sliceProfilesOpt.get()
1121
1122                                     LOGGER.debug("getNSSIAssociatedProfiles: sliceProfiles.getSliceProfile().size() = " + sliceProfiles.getSliceProfile().size())
1123                                     LOGGER.debug("getNSSIAssociatedProfiles: givenSliceProfileId = " + givenSliceProfileId)
1124                                     for(SliceProfile sliceProfile: sliceProfiles.getSliceProfile()) {
1125                                         LOGGER.debug("getNSSIAssociatedProfiles: sliceProfile.getProfileId() = " + sliceProfile.getProfileId())
1126                                         if(sliceProfile.getProfileId().equals(givenSliceProfileId)) { // Slice profile id equals to received slice profile id
1127                                             currentNSSI['sliceProfileInstanceUri'] = sliceProfileInstanceUri
1128                                         }
1129
1130                                     }
1131
1132                                     associatedProfiles.addAll(sliceProfiles.getSliceProfile()) // Adds all slice profiles
1133                                 }
1134
1135                             }
1136                         }
1137                         else {
1138                             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No Slice Profile Instance found")
1139                         }
1140                     }
1141                 }
1142                 else {
1143                     exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No relationships found for Allotted Resource")
1144                 }
1145
1146             }
1147         }
1148         else {
1149             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No relationships  found for nssi id = " + nssiId)
1150         }
1151
1152         checkAssociatedProfiles(execution, associatedProfiles, nssi)
1153
1154         currentNSSI['associatedProfiles'] =  associatedProfiles
1155
1156         LOGGER.debug("${getPrefix()} Exit getNSSIAssociatedProfiles")
1157     }
1158
1159
1160     void checkAssociatedProfiles(DelegateExecution execution, List<SliceProfile> associatedProfiles, ServiceInstance nssi) {}
1161
1162
1163     /**
1164      * Removes Slice Profile association with NSSI
1165      * @param execution
1166      */
1167     void removeSPAssociationWithNSSI(DelegateExecution execution) {
1168         LOGGER.debug("${getPrefix()} Start removeSPAssociationWithNSSI")
1169
1170         AAIResourcesClient client = getAAIClient()
1171
1172         def currentNSSI = execution.getVariable("currentNSSI")
1173
1174         String nssiId = currentNSSI['nssiId']
1175         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
1176
1177         String isTerminateNSSIVar = execution.getVariable("isTerminateNSSI" )
1178
1179         boolean isTerminateNSSI = Boolean.parseBoolean(isTerminateNSSIVar)
1180
1181         AAIResourceUri sliceProfileInstanceUri = null
1182         if(!isTerminateNSSI) { // In case of NSSI non-termination associated Slice Profile Instance should be presented
1183             def spURI = currentNSSI['sliceProfileInstanceUri']
1184             if(spURI != null) {
1185                 sliceProfileInstanceUri = (AAIResourceUri)spURI
1186             }
1187             else {
1188                 String msg = "Slice Profile association with NSSI was already removed"
1189                 LOGGER.info(msg)
1190             }
1191         }
1192
1193         // Removes SLice Profile Instance association with NSSI
1194         if(sliceProfileInstanceUri != null) { // NSSI should not be terminated
1195             try {
1196                 client.disconnect(nssiUri, sliceProfileInstanceUri)
1197             }
1198             catch (Exception e) {
1199                 exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance association with NSSI dosconnect call: " + e.getMessage())
1200             }
1201         }
1202
1203
1204         LOGGER.debug("${getPrefix()} Exit removeSPAssociationWithNSSI")
1205     }
1206
1207
1208     /**
1209      * Deletes Slice Profile Instance
1210      * @param execution
1211      */
1212     void deleteSliceProfileInstance(DelegateExecution execution) {
1213         LOGGER.debug("${getPrefix()} Start deleteSliceProfileInstance")
1214
1215         AAIResourcesClient client = getAAIClient()
1216
1217         def currentNSSI = execution.getVariable("currentNSSI")
1218
1219         String isTerminateNSSIVar = execution.getVariable("isTerminateNSSI" )
1220
1221         boolean isTerminateNSSI = Boolean.parseBoolean(isTerminateNSSIVar)
1222
1223         AAIResourceUri sliceProfileInstanceUri = null
1224         if(!isTerminateNSSI) { // In case of NSSI non-termination associated Slice Profile Instance should be presented
1225             def spURI = currentNSSI['sliceProfileInstanceUri']
1226             if(spURI != null) {
1227                 sliceProfileInstanceUri = (AAIResourceUri)spURI
1228             }
1229             else {
1230                 String msg = "Slice Profile instance was already deleted"
1231                 LOGGER.info(msg)
1232             }
1233         }
1234
1235         if(sliceProfileInstanceUri != null) {
1236             try {
1237                 client.delete(sliceProfileInstanceUri)
1238             } catch (Exception e) {
1239                 exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance delete call: " + e.getMessage())
1240             }
1241         }
1242
1243         LOGGER.debug("${getPrefix()} Exit deleteSliceProfileInstance")
1244     }
1245
1246
1247     /**
1248      * Prepares update resource operation status
1249      * @param execution
1250      */
1251     void prepareUpdateResourceOperationStatus(DelegateExecution execution) {
1252         LOGGER.debug("${getPrefix()} Start updateServiceOperationStatus")
1253
1254         def currentNSSI = execution.getVariable("currentNSSI")
1255
1256         //Prepare Update Status for PUT failure and success
1257         String isTimeOutVar = execution.getVariable("isTimeOut")
1258         if(!isBlank(isTimeOutVar) && isTimeOutVar.equals("YES")) {
1259             LOGGER.error("TIMEOUT - SO PUT Failure")
1260             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "SO PUT Failure")
1261         } else {
1262             execution.setVariable("progress", "100")
1263             execution.setVariable("status", "finished")
1264             execution.setVariable("operationContent", "${getAction()} Core NSSI successful.")
1265         }
1266
1267         setResourceOperationStatus(execution, "finished", "100", "Core NSSI ${getAction()} successful")
1268
1269         LOGGER.debug("${getPrefix()} Exit updateServiceOperationStatus")
1270     }
1271
1272
1273     /**
1274      * Prepares ResourceOperation status
1275      * @param execution
1276      * @param operationType
1277      */
1278     void setResourceOperationStatus(DelegateExecution execution, String status, String progress, String statusDesc) {
1279         LOGGER.debug("${getPrefix()} Start setResourceOperationStatus")
1280
1281         def currentNSSI = execution.getVariable("currentNSSI")
1282
1283         String serviceId = currentNSSI['nsiId']
1284         String jobId = execution.getVariable("jobId")
1285         String nsiId = currentNSSI['nsiId']
1286         String operationType = execution.getVariable("operationType")
1287         String resourceInstanceId = currentNSSI['nssiId']
1288
1289         ServiceInstance nssi = (ServiceInstance) currentNSSI['nssi']
1290         String modelUuid = nssi.getModelVersionId()
1291
1292         ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
1293         resourceOperationStatus.setServiceId(serviceId)
1294         resourceOperationStatus.setOperationId(jobId)
1295         resourceOperationStatus.setResourceTemplateUUID(modelUuid)
1296         resourceOperationStatus.setOperType(operationType)
1297         resourceOperationStatus.setResourceInstanceID(resourceInstanceId)
1298         resourceOperationStatus.setStatus(status)
1299         resourceOperationStatus.setProgress(progress)
1300         resourceOperationStatus.setStatusDescription(statusDesc)
1301         requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
1302
1303         LOGGER.debug("${getPrefix()} Exit setResourceOperationStatus")
1304     }
1305
1306
1307     /**
1308      * Prepares failed operation status update
1309      * @param execution
1310      */
1311     void prepareFailedOperationStatusUpdate(DelegateExecution execution) {
1312         LOGGER.debug("${getPrefix()} Start prepareFailedOperationStatusUpdate")
1313
1314         setResourceOperationStatus(execution, "failed", "0", "Core NSSI ${getAction()} Failed")
1315
1316         LOGGER.debug("${getPrefix()} Exit prepareFailedOperationStatusUpdate")
1317     }
1318
1319
1320     /**
1321      * Gets progress status of ServiceInstance PUT operation
1322      * @param execution
1323      */
1324     public void getPUTServiceInstanceProgress(DelegateExecution execution) {
1325         LOGGER.debug("${getPrefix()} Start getPUTServiceInstanceProgress")
1326
1327         def currentNSSI = execution.getVariable("currentNSSI")
1328
1329         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
1330
1331         String url = currentNSSI['requestSelfLink']
1332
1333         String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
1334
1335         String basicAuth =  UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution)
1336
1337         def authHeader = ""
1338         String basicAuthValue = utils.getBasicAuth(basicAuth, msoKey)
1339
1340         getProgress(execution, url, basicAuthValue, "putStatus")
1341
1342         LOGGER.debug("${getPrefix()} Exit getPUTServiceInstanceProgress")
1343     }
1344
1345
1346     void getProgress(DelegateExecution execution, String url, String authHeader, String statusVariableName) {
1347         LOGGER.debug("${getPrefix()} Start getProgress")
1348
1349         LOGGER.debug("getProgress: url = " + url)
1350         LOGGER.debug("getProgress: authHeader = " + authHeader)
1351
1352         String msg=""
1353         try {
1354
1355             HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.SO)
1356             httpClient.addAdditionalHeader("Authorization", authHeader)
1357             httpClient.addAdditionalHeader("Accept", "application/json")
1358
1359             Response response = httpClient.get()
1360             int responseCode = response.getStatus()
1361           //  execution.setVariable("GetServiceOrderResponseCode", responseCode)
1362             LOGGER.debug("Get ServiceOrder response code is: " + responseCode)
1363
1364             String soResponse = ""
1365             if(response.hasEntity()) {
1366                 soResponse = response.readEntity(String.class)
1367          //       execution.setVariable("GetServiceOrderResponse", extApiResponse)
1368                 LOGGER.debug("Create response body is: " + soResponse)
1369             }
1370
1371             //Process Response //200 OK 201 CREATED 202 ACCEPTED
1372             if (responseCode >= 200 && responseCode < 204) {
1373                 LOGGER.debug("Get Create ServiceOrder Received a Good Response")
1374                 String requestState = jsonUtil.getJsonValue(soResponse, "request.requestStatus.requestState")
1375
1376                 /*
1377                 JSONArray items = responseObj.getJSONArray("orderItem")
1378                 JSONObject item = items.get(0)
1379                 JSONObject service = item.get("service")
1380                 String networkServiceId = service.get("id")
1381                 if (networkServiceId == null || networkServiceId.equals("null")) {
1382                     prepareFailedOperationStatusUpdate(execution)
1383                     return
1384                 }
1385
1386                 execution.setVariable("networkServiceId", networkServiceId)
1387                 String serviceOrderState = item.get("state")
1388                 execution.setVariable("ServiceOrderState", serviceOrderState) */
1389
1390                 // Get serviceOrder State and process progress
1391                 if("ACKNOWLEDGED".equalsIgnoreCase(requestState)) {
1392                     execution.setVariable(statusVariableName, "processing")
1393                 }
1394                 else if("IN_PROGRESS".equalsIgnoreCase(requestState)) {
1395                     execution.setVariable(statusVariableName, "processing")
1396                 }
1397                 else if("COMPLETE".equalsIgnoreCase(requestState)) {
1398                     execution.setVariable(statusVariableName, "completed")
1399                 }
1400                 else if("FAILED".equalsIgnoreCase(requestState)) {
1401                     msg = "ServiceOrder failed"
1402                     exceptionUtil.buildAndThrowWorkflowException(execution, 7000,  msg)
1403                 }
1404                 else if("REJECTED".equalsIgnoreCase(requestState)) {
1405                     prepareFailedOperationStatusUpdate(execution)
1406                 }
1407                 else {
1408                     msg = "ServiceOrder failed"
1409                     exceptionUtil.buildAndThrowWorkflowException(execution, 7000,  msg)
1410                 }
1411             }
1412             else{
1413                 msg = "Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode
1414                 prepareFailedOperationStatusUpdate(execution)
1415             }
1416
1417         }catch(Exception e){
1418             exceptionUtil.buildAndThrowWorkflowException(execution, 7000,  e.getMessage())
1419         }
1420
1421         LOGGER.debug("${getPrefix()} Exit getProgress")
1422     }
1423
1424
1425
1426     /**
1427      * Delays 5 sec
1428      * @param execution
1429      */
1430     void timeDelay(DelegateExecution execution) {
1431         LOGGER.debug("${getPrefix()} Start timeDelay")
1432
1433         try {
1434             LOGGER.debug("${getPrefix()} timeDelay going to sleep for 5 sec")
1435
1436             Thread.sleep(5000)
1437
1438             LOGGER.debug("${getPrefix()} ::: timeDelay wakeup after 5 sec")
1439         } catch(InterruptedException e) {
1440             LOGGER.error("${getPrefix()} ::: timeDelay exception" + e)
1441         }
1442
1443         LOGGER.debug("${getPrefix()} Exit timeDelay")
1444     }
1445
1446
1447     void postProcessRequest(DelegateExecution execution) {
1448         LOGGER.debug("${getPrefix()} Start postProcessRequest")
1449
1450         execution.removeVariable("currentNSSI")
1451
1452         LOGGER.debug("***** ${getPrefix()} Exit postProcessRequest")
1453     }
1454
1455
1456
1457     /**
1458      * Returns AAI client
1459      * @return AAI client
1460      */
1461     AAIResourcesClient getAAIClient() {
1462         return new AAIResourcesClient()
1463     }
1464
1465
1466     ExternalAPIUtilFactory getExternalAPIUtilFactory() {
1467         return new ExternalAPIUtilFactory()
1468     }
1469
1470
1471     /**
1472      * Returns Catalog DB Util Factory
1473      * @return ew CatalogDbUtilsFactory()
1474      */
1475     CatalogDbUtilsFactory getCatalogDbUtilsFactory() {
1476         return new CatalogDbUtilsFactory()
1477     }
1478
1479
1480     private String getPrefix() {
1481         return PREFIX
1482     }
1483
1484     String getAction() {
1485         return ""
1486     }
1487 }