e225c360ed795785a943216c3a1ad35178d21d15
[so.git] /
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.DelegateExecution
25 import org.onap.aai.domain.yang.CloudRegion
26 import org.onap.aai.domain.yang.GenericVnf
27 import org.onap.aai.domain.yang.ModelVer
28 import org.onap.aai.domain.yang.ServiceInstance
29 import org.onap.aai.domain.yang.ServiceSubscription
30 import org.onap.aai.domain.yang.SliceProfile
31 import org.onap.aai.domain.yang.Tenant
32 import org.onap.aai.domain.yang.VfModule
33 import org.onap.aaiclient.client.aai.AAIObjectType
34 import org.onap.aaiclient.client.aai.AAIResourcesClient
35 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
36 import org.onap.aaiclient.client.aai.entities.Relationships
37 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
38 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
39 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
40 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
41 import org.onap.logging.filter.base.ONAPComponents
42 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
43 import org.onap.so.bpmn.common.scripts.ExceptionUtil
44 import org.onap.so.bpmn.common.scripts.RequestDBUtil
45 import org.onap.so.bpmn.core.UrnPropertiesReader
46 import org.onap.so.bpmn.core.json.JsonUtils
47 import org.onap.so.client.HttpClient
48 import org.onap.so.db.request.beans.OperationStatus
49 import org.onap.so.requestsdb.RequestsDbConstant
50 import org.onap.so.serviceinstancebeans.CloudConfiguration
51 import org.onap.so.serviceinstancebeans.LineOfBusiness
52 import org.onap.so.serviceinstancebeans.ModelInfo
53 import org.onap.so.serviceinstancebeans.ModelType
54 import org.onap.so.serviceinstancebeans.OwningEntity
55 import org.onap.so.serviceinstancebeans.Project
56 import org.onap.so.serviceinstancebeans.RequestDetails
57 import org.onap.so.serviceinstancebeans.RequestInfo
58 import org.onap.so.serviceinstancebeans.RequestParameters
59 import org.onap.so.serviceinstancebeans.Resources
60 import org.onap.so.serviceinstancebeans.Service
61 import org.onap.so.serviceinstancebeans.SubscriberInfo
62 import org.onap.so.serviceinstancebeans.VfModules
63 import org.onap.so.serviceinstancebeans.Vnfs
64 import org.slf4j.Logger
65 import org.slf4j.LoggerFactory
66
67 import javax.ws.rs.core.Response
68
69
70  class DoCommonCoreNSSI extends AbstractServiceTaskProcessor {
71
72     private final String PREFIX ="DoCommonCoreNSSI"
73
74     private static final Logger LOGGER = LoggerFactory.getLogger( DoCommonCoreNSSI.class)
75
76     private JsonUtils jsonUtil = new JsonUtils()
77     private ExceptionUtil exceptionUtil = new ExceptionUtil()
78     private RequestDBUtil requestDBUtil = new RequestDBUtil()
79
80     @Override
81     void preProcessRequest(DelegateExecution execution) {
82         LOGGER.trace("${getPrefix()} Start preProcessRequest")
83
84         def currentNSSI = execution.getVariable("currentNSSI")
85         if (!currentNSSI) {
86             String msg = "currentNSSI is null"
87             LOGGER.error(msg)
88             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
89         }
90
91         LOGGER.trace("***** ${getPrefix()} Exit preProcessRequest")
92     }
93
94
95     /**
96      * Queries Network Service Instance in AAI
97      * @param execution
98      */
99     void getNetworkServiceInstance(DelegateExecution execution) {
100         LOGGER.trace("${getPrefix()} Start getNetworkServiceInstance")
101
102         AAIResourcesClient client = getAAIClient()
103
104         def currentNSSI = execution.getVariable("currentNSSI")
105
106         String nssiId = currentNSSI['nssiId']
107
108         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
109         Optional<ServiceInstance> nssiOpt = client.get(ServiceInstance.class, nssiUri)
110
111         if (nssiOpt.isPresent()) {
112             ServiceInstance nssi = nssiOpt.get()
113             currentNSSI['nssi'] = nssi
114
115             ServiceInstance networkServiceInstance = handleNetworkInstance(execution, nssiId, nssiUri, client)
116             currentNSSI['networkServiceInstance'] = networkServiceInstance
117         }
118         else {
119             String msg = String.format("NSSI %s not found in AAI", nssiId)
120             LOGGER.error(msg)
121             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
122         }
123
124         LOGGER.trace("${getPrefix()} Exit getNetworkServiceInstance")
125     }
126
127
128     /**
129      * Handles Network Service
130      * @param nssiId
131      * @param nssiUri
132      * @param client
133      * @return Network Service Instance
134      */
135     private ServiceInstance handleNetworkInstance(DelegateExecution execution, String nssiId, AAIResourceUri nssiUri, AAIResourcesClient client ) {
136         ServiceInstance networkServiceInstance = null
137
138         def currentNSSI = execution.getVariable("currentNSSI")
139
140         AAIResultWrapper wrapper = client.get(nssiUri)
141         Optional<Relationships> relationships = wrapper.getRelationships()
142
143         if (relationships.isPresent()) {
144             for (AAIResourceUri networkServiceInstanceUri : relationships.get().getRelatedUris(Types.SERVICE_INSTANCE)) {
145                 Optional<ServiceInstance> networkServiceInstanceOpt = client.get(ServiceInstance.class, networkServiceInstanceUri)
146                 if (networkServiceInstanceOpt.isPresent()) {
147                     networkServiceInstance = networkServiceInstanceOpt.get()
148
149                     if (networkServiceInstance.getServiceRole() == "Network Service") { // Network Service role
150                         currentNSSI['networkServiceInstanceUri'] = networkServiceInstanceUri
151                         break
152                     }
153                 }
154                 else {
155                     String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
156                     LOGGER.error(msg)
157                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
158                 }
159             }
160         }
161         else {
162             String msg = String.format("No relationship presented for NSSI %s in AAI", nssiId)
163             LOGGER.error(msg)
164             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
165         }
166
167         if(networkServiceInstance == null) {
168             String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
169             LOGGER.error(msg)
170             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
171         }
172
173         return networkServiceInstance
174     }
175
176
177     /**
178      * Queries constitute VNF from Network Service Instance
179      * @param execution
180      */
181     void getConstituteVNFFromNetworkServiceInst(DelegateExecution execution) {
182         LOGGER.trace("${getPrefix()} Start getConstituteVNFFromNetworkServiceInst")
183
184         def currentNSSI = execution.getVariable("currentNSSI")
185
186         AAIResourcesClient client = getAAIClient()
187
188         AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
189         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri);
190         Optional<Relationships> relationships = wrapper.getRelationships()
191         if (relationships.isPresent()) {
192             for (AAIResourceUri constituteVnfUri : relationships.get().getRelatedUris(Types.GENERIC_VNF)) {
193                 currentNSSI['constituteVnfUri'] = constituteVnfUri
194                 Optional<GenericVnf> constituteVnfOpt = client.get(GenericVnf.class, constituteVnfUri)
195                 if(constituteVnfOpt.isPresent()) {
196                     GenericVnf constituteVnf = constituteVnfOpt.get()
197                     currentNSSI['constituteVnf'] = constituteVnf
198                 }
199                 else {
200                     String msg = String.format("No constitute VNF found for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
201                     LOGGER.error(msg)
202                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
203                 }
204
205                 break  // Should be only one constitute VNF
206             }
207         }
208         else {
209             String msg = String.format("No relationship presented for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
210             LOGGER.error(msg)
211             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
212         }
213
214         LOGGER.trace("${getPrefix()} Exit getConstituteVNFFromNetworkServiceInst")
215
216     }
217
218
219     /**
220      * Retrieves NSSI associated profiles from AAI
221      * @param execution
222      */
223     void getNSSIAssociatedProfiles(DelegateExecution execution) {
224         LOGGER.trace("${getPrefix()} Start getNSSIAssociatedProfiles")
225
226         def currentNSSI = execution.getVariable("currentNSSI")
227
228         ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
229
230         List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
231
232         if(associatedProfiles.isEmpty()) {
233             String msg = String.format("No associated profiles found for NSSI %s in AAI", nssi.getServiceInstanceId())
234             LOGGER.error(msg)
235             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
236         }
237         else {
238             currentNSSI['associatedProfiles'] =  associatedProfiles
239         }
240
241         LOGGER.trace("${getPrefix()} Exit getNSSIAssociatedProfiles")
242     }
243
244
245     /**
246      * Calculates a final list of S-NSSAI
247      * @param execution
248      */
249     void calculateSNSSAI(DelegateExecution execution) {
250         LOGGER.trace("${getPrefix()} Start calculateSNSSAI")
251
252         def currentNSSI = execution.getVariable("currentNSSI")
253
254         List<SliceProfile> associatedProfiles = (List<SliceProfile>)currentNSSI['associatedProfiles']
255
256         String currentSNSSAI = currentNSSI['S-NSSAI']
257
258         List<String> snssais = new ArrayList<>()
259
260         String isCreateSliceProfileInstanceVar = execution.getVariable("isCreateSliceProfileInstance" )
261
262         boolean isCreateSliceProfileInstance = Boolean.parseBoolean(isCreateSliceProfileInstanceVar)
263
264         if(isCreateSliceProfileInstance) { // Slice Profile Instance has to be created
265             for (SliceProfile associatedProfile : associatedProfiles) {
266                 snssais.add(associatedProfile.getSNssai())
267             }
268
269             snssais.add(currentSNSSAI)
270         }
271         else { // Slice profile instance has to be deleted
272             for (SliceProfile associatedProfile : associatedProfiles) {
273                 if (!associatedProfile.getSNssai().equals(currentSNSSAI)) { // not current S-NSSAI
274                     snssais.add(associatedProfile.getSNssai())
275                 } else {
276                     currentNSSI['sliceProfileS-NSSAI'] = associatedProfile
277                 }
278             }
279         }
280
281         currentNSSI['S-NSSAIs'] = snssais
282
283         LOGGER.trace("${getPrefix()} Exit calculateSNSSAI")
284     }
285
286
287     /**
288      * Invoke PUT Service Instance API
289      * @param execution
290      */
291     void invokePUTServiceInstance(DelegateExecution execution) {
292         LOGGER.trace("${getPrefix()} Start invokePUTServiceInstance")
293
294         def currentNSSI = execution.getVariable("currentNSSI")
295
296         try {
297             //url:/onap/so/infra/serviceInstantiation/v7/serviceInstances/{serviceInstanceId}/vnfs/{vnfId}"
298             def nsmfЕndpoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution) // ???
299
300             ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
301
302             GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
303
304             String url = String.format("${nsmfЕndpoint}/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s", networkServiceInstance.getServiceInstanceId(), constituteVnf.getVnfId())
305
306             String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
307             String basicAuth =  UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
308
309             def authHeader = ""
310             String basicAuthValue = encryptBasicAuth(basicAuth, msoKey) //utils.encrypt(basicAuth, msoKey)
311             String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msoKey) //utils.getBasicAuth(basicAuthValue, msoKey)
312
313             String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
314             if(errorCode == null || errorCode.isEmpty()) { // No error
315                 authHeader = responseAuthHeader
316             }
317             else {
318                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
319             }
320
321             def requestDetails = ""
322             String prepareRequestDetailsResponse = prepareRequestDetails(execution)
323             errorCode = jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorCode")
324             if(errorCode == null || errorCode.isEmpty()) { // No error
325                 requestDetails = prepareRequestDetailsResponse
326             }
327             else {
328                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorMessage"))
329             }
330
331             String callPUTServiceInstanceResponse = callPUTServiceInstance(url, authHeader, requestDetails)
332             String putServiceInstanceResponse = ""
333
334             if(errorCode == null || errorCode.isEmpty()) { // No error
335                 putServiceInstanceResponse = callPUTServiceInstanceResponse // check the response ???
336             }
337             else {
338                 LOGGER.error(jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
339                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
340             }
341
342         } catch (any) {
343             String msg = "Exception in ${getPrefix()}.invokePUTServiceInstance. " + any.getCause()
344             LOGGER.error(msg)
345             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
346         }
347
348         LOGGER.trace("${getPrefix()} Exit invokePUTServiceInstance")
349     }
350
351
352     String callPUTServiceInstance(String url, String authHeader, String requestDetailsStr) {
353         String errorCode = ""
354         String errorMessage = ""
355         String response
356
357         try {
358             HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.EXTERNAL)
359             httpClient.addAdditionalHeader("Authorization", authHeader)
360             httpClient.addAdditionalHeader("Accept", "application/json")
361
362             Response httpResponse = httpClient.put(requestDetailsStr) // check http code ???
363
364
365             if (httpResponse.hasEntity()) {
366                 response = httpResponse.readEntity(String.class)
367             }
368             else {
369                 errorCode = 500
370                 errorMessage = "No response received."
371
372                 response =  "{\n" +
373                         " \"errorCode\": \"${errorCode}\",\n" +
374                         " \"errorMessage\": \"${errorMessage}\"\n" +
375                         "}"
376             }
377         }
378         catch (any) {
379             String msg = "Exception in ${getPrefix()}.invokePUTServiceInstance. " + any.getCause()
380             LOGGER.error(msg)
381
382             response =  "{\n" +
383                     " \"errorCode\": \"7000\",\n" +
384                     " \"errorMessage\": \"${msg}\"\n" +
385                     "}"
386
387         }
388
389         return response
390
391     }
392
393
394     /**
395      * Prepare model info
396      * @param execution
397      * @param requestDetails
398      * @return ModelInfo
399      */
400     ModelInfo prepareModelInfo(DelegateExecution execution) {
401
402         def currentNSSI = execution.getVariable("currentNSSI")
403         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
404
405         ModelInfo modelInfo = new ModelInfo()
406
407         modelInfo.setModelType(ModelType.service)
408         modelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
409
410         AAIResourcesClient client = getAAIClient()
411
412         AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(networkServiceInstance.getModelInvariantId()).modelVer(networkServiceInstance.getModelVersionId()))
413         Optional<ModelVer> modelVerOpt = client.get(ModelVer.class, modelVerUrl)
414
415         if (modelVerOpt.isPresent()) {
416             modelInfo.setModelVersionId(modelVerOpt.get().getModelVersionId())
417             modelInfo.setModelName(modelVerOpt.get().getModelName())
418             modelInfo.setModelVersion(modelVerOpt.get().getModelVersion())
419         }
420
421         return modelInfo
422     }
423
424
425     /**
426      * Prepares subscriber info
427      * @param execution
428      * @return SubscriberInfo
429      */
430     SubscriberInfo prepareSubscriberInfo(DelegateExecution execution) {
431         def currentNSSI = execution.getVariable("currentNSSI")
432
433         String globalSubscriberId = currentNSSI['globalSubscriberId']
434
435         String subscriberName = currentNSSI['subscriberName']
436
437         SubscriberInfo subscriberInfo = new SubscriberInfo()
438         subscriberInfo.setGlobalSubscriberId(globalSubscriberId)
439         subscriberInfo.setSubscriberName(subscriberName)
440
441         /*
442         AAIResourcesClient client = getAAIClient()
443
444         Customer customer = null
445
446         AAIResourceUri networkServiceInstanceUri = currentNSSI['networkServiceInstanceUri']
447         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
448         Optional<Relationships> serviceSubscriptionRelationshipsOps = wrapper.getRelationships()
449         if(serviceSubscriptionRelationshipsOps.isPresent()) {
450             List<AAIResourceUri> serviceSubscriptionRelatedAAIUris = serviceSubscriptionRelationshipsOps.get().getRelatedUris(Types.SERVICE_SUBSCRIPTION)
451             if(!(serviceSubscriptionRelatedAAIUris == null || serviceSubscriptionRelatedAAIUris.isEmpty())) {
452                 AAIResourceUri serviceSubscriptionUri = serviceSubscriptionRelatedAAIUris.get(0) // Many-To-One relation
453                 Optional<ServiceSubscription> serviceSubscriptionOpt = client.get(ServiceSubscription.class, serviceSubscriptionUri)
454
455                 if(serviceSubscriptionOpt.isPresent()) {
456                     currentNSSI['serviceSubscription'] = serviceSubscriptionOpt.get()
457                 }
458
459                 wrapper = client.get(serviceSubscriptionUri)
460                 Optional<Relationships> customerRelationshipsOps = wrapper.getRelationships()
461                 if(customerRelationshipsOps.isPresent()) {
462                     List<AAIResourceUri> customerRelatedAAIUris = customerRelationshipsOps.get().getRelatedUris(Types.CUSTOMER)
463                     if(!(customerRelatedAAIUris == null || customerRelatedAAIUris.isEmpty())) {
464                         Optional<Customer> customerOpt = client.get(Customer.class, customerRelatedAAIUris.get(0)) // Many-To-One relation
465                         if(customerOpt.isPresent()) {
466                             customer = customerOpt.get()
467                             subscriberInfo.setSubscriberName(customer.getSubscriberName())
468                         }
469                     }
470                 }
471             }
472
473         } */
474
475         return subscriberInfo
476     }
477
478
479     /**
480      * Prepares Request Info
481      * @param execution
482      * @return RequestInfo
483      */
484     RequestInfo prepareRequestInfo(DelegateExecution execution, ServiceInstance networkServiceInstance) {
485         def currentNSSI = execution.getVariable("currentNSSI")
486
487         String serviceId = currentNSSI['serviceId']
488
489         RequestInfo requestInfo = new RequestInfo()
490
491         requestInfo.setInstanceName(networkServiceInstance.getServiceInstanceName())
492         requestInfo.setSource("VID")
493         requestInfo.setProductFamilyId(serviceId)
494         requestInfo.setRequestorId("NBI")
495
496         return requestInfo
497     }
498
499
500     /**
501      * Prepares Model Info
502      * @param networkServiceInstance
503      * @param modelInfo
504      * @return ModelInfo
505      */
506     ModelInfo prepareServiceModelInfo(ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
507
508         ModelInfo serviceModelInfo = new ModelInfo()
509         serviceModelInfo.setModelType(ModelType.service)
510         serviceModelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
511
512         serviceModelInfo.setModelVersionId(modelInfo.getModelVersionId())
513         serviceModelInfo.setModelName(modelInfo.getModelName())
514         serviceModelInfo.setModelVersion(modelInfo.getModelVersion())
515
516         return serviceModelInfo
517     }
518
519
520     /**
521      * Prepares Cloud configuration
522      * @param execution
523      * @return CloudConfiguration
524      */
525     CloudConfiguration prepareCloudConfiguration(DelegateExecution execution) {
526         def currentNSSI = execution.getVariable("currentNSSI")
527
528         CloudConfiguration cloudConfiguration = new CloudConfiguration()
529
530         AAIResourcesClient client = getAAIClient()
531
532         AAIResourceUri constituteVnfUri = currentNSSI['constituteVnfUri']
533         AAIResultWrapper wrapper = client.get(constituteVnfUri)
534         Optional<Relationships> cloudRegionRelationshipsOps = wrapper.getRelationships()
535
536         if(cloudRegionRelationshipsOps.isPresent()) {
537             List<AAIResourceUri> cloudRegionRelatedAAIUris = cloudRegionRelationshipsOps.get().getRelatedUris(Types.CLOUD_REGION)
538             if (!(cloudRegionRelatedAAIUris == null || cloudRegionRelatedAAIUris.isEmpty())) {
539                 AAIResourceUri cloudRegionRelatedAAIUri = cloudRegionRelatedAAIUris.get(0)
540                 currentNSSI['cloudRegionRelatedAAIUri'] = cloudRegionRelatedAAIUri
541
542                 Optional<CloudRegion> cloudRegionrOpt = client.get(CloudRegion.class, cloudRegionRelatedAAIUris.get(0))
543                 CloudRegion cloudRegion = null
544                 if (cloudRegionrOpt.isPresent()) {
545                     cloudRegion = cloudRegionrOpt.get()
546                     cloudConfiguration.setLcpCloudRegionId(cloudRegion.getCloudRegionId())
547                     for (Tenant tenant : cloudRegion.getTenants().getTenant()) {
548                         cloudConfiguration.setTenantId(tenant.getTenantId())
549                         break // only one is required
550                     }
551
552                     cloudConfiguration.setCloudOwner(cloudRegion.getCloudOwner())
553                 }
554             }
555         }
556
557         return cloudConfiguration
558     }
559
560
561     /**
562      * Prepares a list of VF Modules
563      * @param execution
564      * @param constituteVnf
565      * @return List<VfModules>
566      */
567     List<VfModules> prepareVfModules(DelegateExecution execution, GenericVnf constituteVnf) {
568
569         AAIResourcesClient client = getAAIClient()
570
571         List<VfModules> vfModuless = new ArrayList<>()
572         for (VfModule vfModule : constituteVnf.getVfModules().getVfModule()) {
573             VfModules vfmodules = new VfModules()
574
575             ModelInfo vfModuleModelInfo = new ModelInfo()
576             vfModuleModelInfo.setModelInvariantUuid(vfModule.getModelInvariantId())
577             vfModuleModelInfo.setModelCustomizationId(vfModule.getModelCustomizationId())
578
579             AAIResourceUri vfModuleUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(vfModule.getModelInvariantId()).modelVer(vfModule.getModelVersionId()))
580
581             Optional<ModelVer> vfModuleModelVerOpt = client.get(ModelVer.class, vfModuleUrl)
582
583             if (vfModuleModelVerOpt.isPresent()) {
584                 vfModuleModelInfo.setModelVersionId(vfModuleModelVerOpt.get().getModelVersionId())
585                 vfModuleModelInfo.setModelName(vfModuleModelVerOpt.get().getModelName())
586                 vfModuleModelInfo.setModelVersion(vfModuleModelVerOpt.get().getModelVersion())
587             }
588             vfmodules.setModelInfo(vfModuleModelInfo)
589
590             vfmodules.setInstanceName(vfModule.getVfModuleName())
591
592             vfModuless.add(vfmodules)
593         }
594
595         return vfModuless
596     }
597
598
599     /**
600      * prepares VNF Model Info
601      * @param execution
602      * @param constituteVnf
603      * @return ModelInfo
604      */
605     ModelInfo prepareVNFModelInfo(DelegateExecution execution, GenericVnf constituteVnf) {
606         ModelInfo vnfModelInfo = new ModelInfo()
607
608         AAIResourcesClient client = getAAIClient()
609
610         vnfModelInfo.setModelInvariantUuid(constituteVnf.getModelInvariantId())
611         vnfModelInfo.setModelCustomizationId(constituteVnf.getModelCustomizationId())
612         vnfModelInfo.setModelInstanceName(constituteVnf.getVnfName())
613
614         AAIResourceUri vnfModelUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(constituteVnf.getModelInvariantId()).modelVer(constituteVnf.getModelVersionId()))
615
616         Optional<ModelVer> vnfModelVerOpt = client.get(ModelVer.class, vnfModelUrl)
617
618         if (vnfModelVerOpt.isPresent()) {
619             vnfModelInfo.setModelVersionId(vnfModelVerOpt.get().getModelVersionId())
620             vnfModelInfo.setModelName(vnfModelVerOpt.get().getModelName())
621             vnfModelInfo.setModelVersion(vnfModelVerOpt.get().getModelVersion())
622         }
623
624         return vnfModelInfo
625     }
626
627
628     List<Map<String, Object>> prepareInstanceParams(DelegateExecution execution) {
629         def currentNSSI = execution.getVariable("currentNSSI")
630
631         List<Map<String, Object>> instanceParams = new ArrayList<>()
632         Map<String, Object> instanceParamsMap = new HashMap<>()
633
634         // Supported S-NSSAI
635         List<String> snssais = (List<String>) currentNSSI['S-NSSAIs']
636
637         ServiceInstance nssi = (ServiceInstance) currentNSSI['nssi']
638
639         String orchStatus = nssi.getOrchestrationStatus()
640
641
642         List<Map<String, String>> snssaiList = new ArrayList<>()
643
644         for(String snssai:snssais) {
645             Map<String, String> snssaisMap = new HashMap<>()
646             snssaisMap.put("snssai", snssai)
647             snssaisMap.put("status", orchStatus)
648             snssaiList.add(snssaisMap)
649         }
650
651         //    Map<String, List<Map<String, String>>> supportedNssaiDetails = new HashMap<>()
652         //    supportedNssaiDetails.put("sNssai", supportedNssaiDetails)
653
654         ObjectMapper mapper = new ObjectMapper()
655
656         String supportedNssaiDetailsStr = mapper.writeValueAsString(snssaiList)
657
658
659         instanceParamsMap.put("k8s-rb-profile-name", "default") // ???
660         instanceParamsMap.put("config-type", "day2") // ???
661         instanceParamsMap.put("supportedNssai", supportedNssaiDetailsStr)
662         instanceParams.add(instanceParamsMap)
663
664         return instanceParams
665     }
666
667     /**
668      * Prepares Resources
669      * @param execution
670      * @return Resources
671      */
672     Resources prepareResources(DelegateExecution execution) {
673         def currentNSSI = execution.getVariable("currentNSSI")
674
675         Resources resources = new Resources()
676
677         // VNFs
678         List<Vnfs> vnfs = new ArrayList<>()
679         // VNF
680         Vnfs vnf = new Vnfs()
681
682         // Line of Business
683         LineOfBusiness lob = new LineOfBusiness()
684         lob.setLineOfBusinessName("VNF")
685         vnf.setLineOfBusiness(lob)
686
687         // Product family ID
688         GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
689         vnf.setProductFamilyId(constituteVnf.getServiceId())
690
691         // Cloud configuration
692         vnf.setCloudConfiguration(prepareCloudConfiguration(execution))
693
694         // VF Modules
695         vnf.setVfModules(prepareVfModules(execution, constituteVnf))
696
697         // Model Info
698         vnf.setModelInfo(prepareVNFModelInfo(execution, constituteVnf))
699
700         // Instance name
701         vnf.setInstanceName(constituteVnf.getVnfName())
702
703         // Instance params
704         vnf.setInstanceParams(prepareInstanceParams(execution))
705
706         // No platform data
707
708         vnfs.add(vnf)
709         resources.setVnfs(vnfs)
710
711         return resources
712     }
713
714
715     /**
716      * Prepare Service
717      * @return Service
718      */
719     Service prepareService(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
720         Service service = new Service()
721
722         // Model Info
723         service.setModelInfo(prepareServiceModelInfo(networkServiceInstance, modelInfo))
724
725         service.setInstanceName(networkServiceInstance.getServiceInstanceName())
726
727         // Resources
728         service.setResources(prepareResources(execution))
729
730         return service
731
732     }
733
734
735     /**
736      * Prepares request parameters
737      * @param execution
738      * @return RequestParameters
739      */
740     RequestParameters prepareRequestParameters(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
741         def currentNSSI = execution.getVariable("currentNSSI")
742
743         RequestParameters requestParameters = new RequestParameters()
744
745         ServiceSubscription serviceSubscription = (ServiceSubscription)currentNSSI['serviceSubscription']
746
747         if(serviceSubscription != null) {
748             requestParameters.setSubscriptionServiceType(serviceSubscription.getServiceType())
749         }
750
751         // User params
752         List<Map<String, Object>> userParams = new ArrayList<>()
753
754         Map<String, Object> userParam = new HashMap<>()
755         userParam.put("Homing_Solution", "none")
756         userParams.add(userParam)
757
758         // Service
759         Map<String, Object> serviceMap = new HashMap<>()
760         serviceMap.put("service", prepareService(execution, networkServiceInstance, modelInfo))
761         userParams.add(serviceMap)
762         requestParameters.setUserParams(userParams)
763
764         return requestParameters
765     }
766
767
768     /**
769      * Prepare Owning Entity
770      * @param execution
771      * @return OwningEntity
772      */
773     OwningEntity prepareOwningEntity(DelegateExecution execution) {
774         def currentNSSI = execution.getVariable("currentNSSI")
775
776         AAIResourcesClient client = getAAIClient()
777
778         AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
779
780         OwningEntity owningEntity = new OwningEntity()
781         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
782         Optional<Relationships> owningEntityRelationshipsOps = wrapper.getRelationships()
783         if (owningEntityRelationshipsOps.isPresent()) {
784             List<AAIResourceUri> owningEntityRelatedAAIUris = owningEntityRelationshipsOps.get().getRelatedUris(Types.OWNING_ENTITY)
785
786             if (!(owningEntityRelatedAAIUris == null || owningEntityRelatedAAIUris.isEmpty())) {
787                 Optional<org.onap.aai.domain.yang.OwningEntity> owningEntityOpt = client.get(org.onap.aai.domain.yang.OwningEntity.class, owningEntityRelatedAAIUris.get(0)) // Many-To-One relation
788                 if (owningEntityOpt.isPresent()) {
789                     owningEntity.setOwningEntityId(owningEntityOpt.get().getOwningEntityId())
790                     owningEntity.setOwningEntityName(owningEntityOpt.get().getOwningEntityName())
791
792                 }
793             }
794         }
795
796         return owningEntity
797     }
798
799
800     /**
801      * Prepares Project
802      * @param execution
803      * @return Project
804      */
805     Project prepareProject(DelegateExecution execution) {
806         def currentNSSI = execution.getVariable("currentNSSI")
807
808         AAIResourcesClient client = getAAIClient()
809
810         Project project = new Project()
811
812         AAIResourceUri cloudRegionRelatedAAIUri = (AAIResourceUri)currentNSSI['cloudRegionRelatedAAIUri']
813
814         if (cloudRegionRelatedAAIUri != null) {
815             AAIResultWrapper wrapper = client.get(cloudRegionRelatedAAIUri)
816             Optional<Relationships> cloudRegionOps = wrapper.getRelationships()
817             if (cloudRegionOps.isPresent()) {
818                 List<AAIResourceUri> projectAAIUris = cloudRegionOps.get().getRelatedUris(Types.PROJECT)
819                 if (!(projectAAIUris == null || projectAAIUris.isEmpty())) {
820                     Optional<org.onap.aai.domain.yang.Project> projectOpt = client.get(org.onap.aai.domain.yang.Project.class, projectAAIUris.get(0))
821                     if (projectOpt.isPresent()) {
822                         project.setProjectName(projectOpt.get().getProjectName())
823                     }
824                 }
825             }
826         }
827
828         return project
829     }
830
831
832     /**
833      * Prepares RequestDetails object
834      * @param execution
835      * @return
836      */
837     String prepareRequestDetails(DelegateExecution execution) {
838         String errorCode = ""
839         String errorMessage = ""
840         String response
841
842         RequestDetails requestDetails = new RequestDetails()
843
844         def currentNSSI = execution.getVariable("currentNSSI")
845
846         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
847
848         try {
849             // Model Info
850             ModelInfo modelInfo = prepareModelInfo(execution)
851             requestDetails.setModelInfo(modelInfo)
852
853             // Subscriber Info
854             requestDetails.setSubscriberInfo(prepareSubscriberInfo(execution))
855
856             // Request Info
857             requestDetails.setRequestInfo(prepareRequestInfo(execution, networkServiceInstance))
858
859             // Request Parameters
860             requestDetails.setRequestParameters(prepareRequestParameters(execution, networkServiceInstance, modelInfo))
861
862             // Cloud configuration
863             requestDetails.setCloudConfiguration(prepareCloudConfiguration(execution))
864
865             // Owning entity
866             requestDetails.setOwningEntity(prepareOwningEntity(execution))
867
868             // Project
869             requestDetails.setProject(prepareProject(execution))
870
871             ObjectMapper mapper = new ObjectMapper()
872
873             response = mapper.writeValueAsString(requestDetails)
874         }
875         catch (any) {
876             String msg = "Exception in ${getPrefix()}.prepareRequestDetails. " + any.getCause()
877             LOGGER.error(msg)
878
879             response =  "{\n" +
880                     " \"errorCode\": \"7000\",\n" +
881                     " \"errorMessage\": \"${msg}\"\n" +
882                     "}"
883
884         }
885
886         return response
887     }
888
889
890     String getAuthHeader(DelegateExecution execution, String basicAuthValue, String msokey) {
891         String response = ""
892         String errorCode = ""
893         String errorMessage = ""
894
895         LOGGER.debug("Obtained BasicAuth username and password for OOF: " + basicAuthValue)
896         try {
897             response = utils.getBasicAuth(basicAuthValue, msokey)
898         } catch (Exception ex) {
899             LOGGER.error("Unable to encode username and password string: ", ex)
900
901             errorCode = "401"
902             errorMessage = "Internal Error - Unable to encode username and password string"
903
904             response =  "{\n" +
905                     " \"errorCode\": \"${errorCode}\",\n" +
906                     " \"errorMessage\": \"${errorMessage}\"\n" +
907                     "}"
908         }
909
910         return response
911     }
912
913
914     String encryptBasicAuth(String basicAuth, String msoKey) {
915         return utils.encrypt(basicAuth, msoKey)
916     }
917
918
919     /**
920      * Removes Slice Profile association with NSSI
921      * @param execution
922      */
923     void removeSPAssociationWithNSSI(DelegateExecution execution) {
924         LOGGER.trace("${getPrefix()} Start removeSPAssociationWithNSSI")
925
926         AAIResourcesClient client = getAAIClient()
927
928         def currentNSSI = execution.getVariable("currentNSSI")
929
930         ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
931
932         String nssiId = currentNSSI['nssiId']
933         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
934
935         List<SliceProfile> associatedProfiles = nssi.getSliceProfiles().getSliceProfile()
936
937         String currentSNSSAI = currentNSSI['S-NSSAI']
938
939         associatedProfiles.removeIf({ associatedProfile -> (associatedProfile.getSNssai().equals(currentSNSSAI)) })
940
941         try {
942             getAAIClient().update(nssiUri, nssi)
943         }catch(Exception e){
944             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile association with NSSI update call: " + e.getMessage())
945         }
946
947         LOGGER.trace("${getPrefix()} Exit removeSPAssociationWithNSSI")
948     }
949
950
951     /**
952      * Deletes Slice Profile Instance
953      * @param execution
954      */
955     void deleteSliceProfileInstance(DelegateExecution execution) {
956         LOGGER.trace("${getPrefix()} Start deleteSliceProfileInstance")
957
958         AAIResourcesClient client = getAAIClient()
959
960         def currentNSSI = execution.getVariable("currentNSSI")
961
962         SliceProfile sliceProfileContainsSNSSAI = (SliceProfile)currentNSSI['sliceProfileS-NSSAI']
963
964         String globalSubscriberId = currentNSSI['globalSubscriberId']
965         String serviceType = currentNSSI['serviceType']
966         String nssiId = currentNSSI['nssiId']
967
968         // global-customer-id, service-type, service-instance-id, profile-id
969         AAIResourceUri sliceProfileUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(serviceType).serviceInstance(nssiId).sliceProfile(sliceProfileContainsSNSSAI.getProfileId()))
970
971         try {
972             getAAIClient().delete(sliceProfileUri)
973         }catch(Exception e){
974             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance delete call: " + e.getMessage())
975         }
976
977         LOGGER.trace("${getPrefix()} Exit deleteSliceProfileInstance")
978     }
979
980
981     /**
982      * Updates operation status
983      * @param execution
984      */
985     void updateServiceOperationStatus(DelegateExecution execution) {
986         LOGGER.trace("${getPrefix()} Start updateServiceOperationStatus")
987
988         def currentNSSI = execution.getVariable("currentNSSI")
989
990         OperationStatus operationStatus = new OperationStatus()
991         operationStatus.setServiceId(currentNSSI['e2eServiceInstanceId'] as String)
992         operationStatus.setOperationId(currentNSSI['operationId'] as String)
993         operationStatus.setOperation(currentNSSI['operationType'] as String)
994         operationStatus.setResult(RequestsDbConstant.Status.FINISHED)
995
996         requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
997
998         LOGGER.trace("${getPrefix()} Exit updateServiceOperationStatus")
999     }
1000
1001
1002     /**
1003      * Returns AAI client
1004      * @return AAI client
1005      */
1006     AAIResourcesClient getAAIClient() {
1007         return new AAIResourcesClient()
1008     }
1009
1010
1011     String getPrefix() {
1012         return PREFIX
1013     }
1014 }