646861a6a0716e0949ce16c96c22e536f77ec4cf
[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.DelegateExecution
25 import org.json.JSONArray
26 import org.json.JSONObject
27 import org.onap.aai.domain.yang.v19.*
28 import org.onap.aaiclient.client.aai.AAIResourcesClient
29 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
30 import org.onap.aaiclient.client.aai.entities.Relationships
31 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
32 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
33 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
34 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
35 import org.onap.logging.filter.base.ONAPComponents
36 import org.onap.so.bpmn.common.scripts.*
37 import org.onap.so.bpmn.core.UrnPropertiesReader
38 import org.onap.so.bpmn.core.json.JsonUtils
39 import org.onap.so.client.HttpClient
40 import org.onap.so.db.request.beans.ResourceOperationStatus
41 import org.onap.so.serviceinstancebeans.*
42 import org.slf4j.Logger
43 import org.slf4j.LoggerFactory
44
45 import javax.ws.rs.core.Response
46
47 import static org.apache.commons.lang3.StringUtils.isBlank
48
49 class DoCommonCoreNSSI extends AbstractServiceTaskProcessor {
50
51     private final String PREFIX ="DoCommonCoreNSSI"
52
53     private static final Logger LOGGER = LoggerFactory.getLogger( DoCommonCoreNSSI.class)
54
55     private JsonUtils jsonUtil = new JsonUtils()
56     private ExceptionUtil exceptionUtil = new ExceptionUtil()
57     private RequestDBUtil requestDBUtil = new RequestDBUtil()
58
59     @Override
60     void preProcessRequest(DelegateExecution execution) {
61         LOGGER.trace("${getPrefix()} Start preProcessRequest")
62
63         def currentNSSI = execution.getVariable("currentNSSI")
64         if (!currentNSSI) {
65             currentNSSI = [:]
66         }
67
68         // NSSI ID
69         String nssiId = execution.getVariable("serviceInstanceID")
70         if (isBlank(nssiId)) {
71             String msg = "NSSI service instance id is null"
72             LOGGER.error(msg)
73             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
74         }
75         else {
76             currentNSSI['nssiId'] = nssiId
77         }
78
79         // NSI ID
80         String nsiId = execution.getVariable("nsiId")
81         if (isBlank(nsiId)) {
82             String msg = "nsiId is null"
83             LOGGER.error(msg)
84             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
85         }
86         else {
87             currentNSSI['nsiId'] = nsiId
88         }
89
90
91         // Slice Profile
92         String sliceProfile = jsonUtil.getJsonValue(execution.getVariable("sliceParams"), "sliceProfile")
93         if (isBlank(sliceProfile)) {
94             String msg = "Slice Profile is null"
95             exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
96         } else {
97             currentNSSI['sliceProfile'] = sliceProfile
98         }
99
100         // S-NSSAI
101         def snssaiList = jsonUtil.StringArrayToList(jsonUtil.getJsonValue(sliceProfile, "snssaiList"))
102
103         String sNssai = snssaiList.get(0)
104         currentNSSI['S-NSSAI'] = sNssai
105
106
107         // Slice Profile id
108         String sliceProfileId = jsonUtil.getJsonValue(sliceProfile, "sliceProfileId")
109         currentNSSI['sliceProfileId'] = sliceProfileId
110
111         execution.setVariable("currentNSSI", currentNSSI)
112
113
114         LOGGER.trace("***** ${getPrefix()} Exit preProcessRequest")
115     }
116
117
118     /**
119      * Queries Network Service Instance in AAI
120      * @param execution
121      */
122     void getNetworkServiceInstance(DelegateExecution execution) {
123         LOGGER.trace("${getPrefix()} Start getNetworkServiceInstance")
124
125         AAIResourcesClient client = getAAIClient()
126
127         def currentNSSI = execution.getVariable("currentNSSI")
128
129         String nssiId = currentNSSI['nssiId']
130
131         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
132         Optional<ServiceInstance> nssiOpt = client.get(ServiceInstance.class, nssiUri)
133
134         if (nssiOpt.isPresent()) {
135             ServiceInstance nssi = nssiOpt.get()
136             currentNSSI['nssi'] = nssi
137
138             ServiceInstance networkServiceInstance = handleNetworkInstance(execution, nssiId, nssiUri, client)
139             currentNSSI['networkServiceInstance'] = networkServiceInstance
140         }
141         else {
142             String msg = String.format("NSSI %s not found in AAI", nssiId)
143             LOGGER.error(msg)
144             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
145         }
146
147         LOGGER.trace("${getPrefix()} Exit getNetworkServiceInstance")
148     }
149
150
151     /**
152      * Handles Network Service
153      * @param nssiId
154      * @param nssiUri
155      * @param client
156      * @return Network Service Instance
157      */
158     private ServiceInstance handleNetworkInstance(DelegateExecution execution, String nssiId, AAIResourceUri nssiUri, AAIResourcesClient client ) {
159         ServiceInstance networkServiceInstance = null
160
161         def currentNSSI = execution.getVariable("currentNSSI")
162
163         AAIResultWrapper wrapper = client.get(nssiUri)
164         Optional<Relationships> relationships = wrapper.getRelationships()
165
166         if (relationships.isPresent()) {
167             for (AAIResourceUri networkServiceInstanceUri : relationships.get().getRelatedUris(Types.SERVICE_INSTANCE)) {
168                 Optional<ServiceInstance> networkServiceInstanceOpt = client.get(ServiceInstance.class, networkServiceInstanceUri)
169                 if (networkServiceInstanceOpt.isPresent()) {
170                     networkServiceInstance = networkServiceInstanceOpt.get()
171
172                     if (networkServiceInstance.getServiceRole() == "Network Service") { // Network Service role
173                         currentNSSI['networkServiceInstanceUri'] = networkServiceInstanceUri
174                         break
175                     }
176                 }
177                 else {
178                     String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
179                     LOGGER.error(msg)
180                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
181                 }
182             }
183         }
184         else {
185             String msg = String.format("No relationship presented for NSSI %s in AAI", nssiId)
186             LOGGER.error(msg)
187             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
188         }
189
190         if(networkServiceInstance == null) {
191             String msg = String.format("No Network Service Instance found for NSSI %s in AAI", nssiId)
192             LOGGER.error(msg)
193             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
194         }
195
196         return networkServiceInstance
197     }
198
199
200     /**
201      * Queries constitute VNF from Network Service Instance
202      * @param execution
203      */
204     void getConstituteVNFFromNetworkServiceInst(DelegateExecution execution) {
205         LOGGER.trace("${getPrefix()} Start getConstituteVNFFromNetworkServiceInst")
206
207         def currentNSSI = execution.getVariable("currentNSSI")
208
209         AAIResourcesClient client = getAAIClient()
210
211         AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
212         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri);
213         Optional<Relationships> relationships = wrapper.getRelationships()
214         if (relationships.isPresent()) {
215             for (AAIResourceUri constituteVnfUri : relationships.get().getRelatedUris(Types.GENERIC_VNF)) {
216                 currentNSSI['constituteVnfUri'] = constituteVnfUri
217                 Optional<GenericVnf> constituteVnfOpt = client.get(GenericVnf.class, constituteVnfUri)
218                 if(constituteVnfOpt.isPresent()) {
219                     GenericVnf constituteVnf = constituteVnfOpt.get()
220                     currentNSSI['constituteVnf'] = constituteVnf
221                 }
222                 else {
223                     String msg = String.format("No constitute VNF found for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
224                     LOGGER.error(msg)
225                     exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
226                 }
227
228                 break  // Should be only one constitute VNF
229             }
230         }
231         else {
232             String msg = String.format("No relationship presented for Network Service Instance %s in AAI", ((ServiceInstance)currentNSSI['networkServiceInstance']).getServiceInstanceId())
233             LOGGER.error(msg)
234             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
235         }
236
237         LOGGER.trace("${getPrefix()} Exit getConstituteVNFFromNetworkServiceInst")
238
239     }
240
241
242     /**
243      * Retrieves NSSI associated profiles from AAI
244      * @param execution
245      */
246     void getNSSIAssociatedProfiles(DelegateExecution execution) {
247         LOGGER.trace("${getPrefix()} Start getNSSIAssociatedProfiles")
248
249         List<SliceProfile> associatedProfiles = new ArrayList<>()
250
251         AAIResourcesClient client = getAAIClient()
252
253         def currentNSSI = execution.getVariable("currentNSSI")
254
255         ServiceInstance nssi = (ServiceInstance)currentNSSI['nssi']
256
257         String nssiId = currentNSSI['nssiId']
258
259         // NSSI
260         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
261         AAIResultWrapper nssiWrapper = client.get(nssiUri)
262         Optional<Relationships> nssiRelationships = nssiWrapper.getRelationships()
263
264         if (nssiRelationships.isPresent()) {
265             // Allotted Resource
266             for (AAIResourceUri allottedResourceUri : nssiRelationships.get().getRelatedUris(Types.ALLOTTED_RESOURCE)) {
267                 AAIResultWrapper arWrapper = client.get(allottedResourceUri)
268                 Optional<Relationships> arRelationships = arWrapper.getRelationships()
269
270                 boolean isFound = false
271                 if(arRelationships.isPresent()) {
272                     // Slice Profile Instance
273                     for (AAIResourceUri sliceProfileInstanceUri : arRelationships.get().getRelatedUris(Types.SERVICE_INSTANCE)) {
274                         Optional<ServiceInstance> sliceProfileInstanceOpt = client.get(ServiceInstance.class, sliceProfileInstanceUri)
275
276                         if (sliceProfileInstanceOpt.isPresent()) {
277                             ServiceInstance sliceProfileInstance = sliceProfileInstanceOpt.get()
278                             if(sliceProfileInstance.getServiceRole().equals("slice-profile-instance")) { // Service instance as a Slice Profile Instance
279                                 associatedProfiles = sliceProfileInstance.getSliceProfiles()?.getSliceProfile()
280
281                                 currentNSSI['sliceProfileInstanceUri'] = sliceProfileInstanceUri
282
283                                 isFound = true
284                                 break // Should be only one
285                             }
286                         }
287                         else {
288                             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No Slice Profile Instance found")
289                         }
290                     }
291                 }
292                 else {
293                     exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No relationships found for Allotted Resource")
294                 }
295
296                 if(isFound) {
297                     break
298                 }
299             }
300         }
301         else {
302             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No relationships  found for nssi id = " + nssiId)
303         }
304
305         if(associatedProfiles.isEmpty()) {
306             String msg = String.format("No associated profiles found for NSSI %s in AAI", nssi.getServiceInstanceId())
307             LOGGER.error(msg)
308             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg)
309         }
310         else {
311             currentNSSI['associatedProfiles'] =  associatedProfiles
312         }
313
314         LOGGER.trace("${getPrefix()} Exit getNSSIAssociatedProfiles")
315     }
316
317
318     /**
319      * Calculates a final list of S-NSSAI
320      * @param execution
321      */
322     void calculateSNSSAI(DelegateExecution execution) {
323         LOGGER.trace("${getPrefix()} Start calculateSNSSAI")
324
325         def currentNSSI = execution.getVariable("currentNSSI")
326
327         List<SliceProfile> associatedProfiles = (List<SliceProfile>)currentNSSI['associatedProfiles']
328
329         String currentSNSSAI = currentNSSI['S-NSSAI']
330
331         List<String> snssais = new ArrayList<>()
332
333         String isCreateSliceProfileInstanceVar = execution.getVariable("isCreateSliceProfileInstance" ) // Not exist in case of Deallocate
334
335         boolean isCreateSliceProfileInstance = Boolean.parseBoolean(isCreateSliceProfileInstanceVar)
336
337         if(isCreateSliceProfileInstance) { // Slice Profile Instance has to be created
338             for (SliceProfile associatedProfile : associatedProfiles) {
339                 snssais.add(associatedProfile.getSNssai())
340             }
341
342             snssais.add(currentSNSSAI)
343         }
344         else { // Slice profile instance has to be deleted
345             for (SliceProfile associatedProfile : associatedProfiles) {
346                 if (!associatedProfile.getSNssai().equals(currentSNSSAI)) { // not current S-NSSAI
347                     snssais.add(associatedProfile.getSNssai())
348                 } else {
349                     currentNSSI['sliceProfileS-NSSAI'] = associatedProfile
350                 }
351             }
352         }
353
354         currentNSSI['S-NSSAIs'] = snssais
355
356         LOGGER.trace("${getPrefix()} Exit calculateSNSSAI")
357     }
358
359
360     /**
361      * Invoke PUT Service Instance API
362      * @param execution
363      */
364     void invokePUTServiceInstance(DelegateExecution execution) {
365         LOGGER.trace("${getPrefix()} Start invokePUTServiceInstance")
366
367         def currentNSSI = execution.getVariable("currentNSSI")
368
369         try {
370             //url:/onap/so/infra/serviceInstantiation/v7/serviceInstances/{serviceInstanceId}"
371             def nsmfЕndPoint = UrnPropertiesReader.getVariable("mso.infra.endpoint.url", execution) // ???
372
373             ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
374
375             String url = String.format("${nsmfЕndPoint}/serviceInstantiation/v7/serviceInstances/%s", networkServiceInstance.getServiceInstanceId())
376
377             currentNSSI['putServiceInstanceURL'] = url
378
379             String msoKey = UrnPropertiesReader.getVariable("mso.msoKey", execution)
380             String basicAuth =  UrnPropertiesReader.getVariable("mso.infra.endpoint.auth", execution)
381
382             def authHeader = ""
383             String basicAuthValue = encryptBasicAuth(basicAuth, msoKey) //utils.encrypt(basicAuth, msoKey)
384             String responseAuthHeader = getAuthHeader(execution, basicAuthValue, msoKey) //utils.getBasicAuth(basicAuthValue, msoKey)
385
386             String errorCode = jsonUtil.getJsonValue(responseAuthHeader, "errorCode")
387             if(errorCode == null || errorCode.isEmpty()) { // No error
388                 authHeader = responseAuthHeader
389             }
390             else {
391                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(responseAuthHeader, "errorMessage"))
392             }
393
394             def requestDetails = ""
395             String prepareRequestDetailsResponse = prepareRequestDetails(execution)
396             errorCode = jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorCode")
397             if(errorCode == null || errorCode.isEmpty()) { // No error
398                 requestDetails = prepareRequestDetailsResponse
399             }
400             else {
401                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(prepareRequestDetailsResponse, "errorMessage"))
402             }
403
404             String callPUTServiceInstanceResponse = callPUTServiceInstance(url, authHeader, requestDetails)
405             String putServiceInstanceResponse = ""
406
407             if(errorCode == null || errorCode.isEmpty()) { // No error
408                 putServiceInstanceResponse = callPUTServiceInstanceResponse
409             }
410             else {
411                 LOGGER.error(jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
412                 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(errorCode), jsonUtil.getJsonValue(callPUTServiceInstanceResponse, "errorMessage"))
413             }
414
415         } catch (any) {
416             String msg = "Exception in ${getPrefix()}.invokePUTServiceInstance. " + any.getCause()
417             LOGGER.error(msg)
418             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
419         }
420
421         LOGGER.trace("${getPrefix()} Exit invokePUTServiceInstance")
422     }
423
424
425     String callPUTServiceInstance(String url, String authHeader, String requestDetailsStr) {
426         String errorCode = ""
427         String errorMessage = ""
428         String response
429
430         try {
431             HttpClient httpClient = getHttpClientFactory().newJsonClient(new URL(url), ONAPComponents.EXTERNAL)
432             httpClient.addAdditionalHeader("Authorization", authHeader)
433             httpClient.addAdditionalHeader("Accept", "application/json")
434
435             Response httpResponse = httpClient.put(requestDetailsStr) // check http code ???
436
437
438             if (httpResponse.hasEntity()) {
439                 response = httpResponse.readEntity(String.class)
440             }
441             else {
442                 errorCode = 500
443                 errorMessage = "No response received."
444
445                 response =  "{\n" +
446                         " \"errorCode\": \"${errorCode}\",\n" +
447                         " \"errorMessage\": \"${errorMessage}\"\n" +
448                         "}"
449             }
450         }
451         catch (any) {
452             String msg = "Exception in ${getPrefix()}.invokePUTServiceInstance. " + any.getCause()
453             LOGGER.error(msg)
454
455             response =  "{\n" +
456                     " \"errorCode\": \"7000\",\n" +
457                     " \"errorMessage\": \"${msg}\"\n" +
458                     "}"
459
460         }
461
462         return response
463
464     }
465
466
467     /**
468      * Prepare model info
469      * @param execution
470      * @param requestDetails
471      * @return ModelInfo
472      */
473     ModelInfo prepareModelInfo(DelegateExecution execution) {
474
475         def currentNSSI = execution.getVariable("currentNSSI")
476         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
477
478         ModelInfo modelInfo = new ModelInfo()
479
480         modelInfo.setModelType(ModelType.service)
481         modelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
482
483         AAIResourcesClient client = getAAIClient()
484
485         AAIResourceUri modelVerUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(networkServiceInstance.getModelInvariantId()).modelVer(networkServiceInstance.getModelVersionId()))
486         Optional<ModelVer> modelVerOpt = client.get(ModelVer.class, modelVerUrl)
487
488         if (modelVerOpt.isPresent()) {
489             modelInfo.setModelVersionId(modelVerOpt.get().getModelVersionId())
490             modelInfo.setModelName(modelVerOpt.get().getModelName())
491             modelInfo.setModelVersion(modelVerOpt.get().getModelVersion())
492         }
493
494         return modelInfo
495     }
496
497
498     /**
499      * Prepares subscriber info
500      * @param execution
501      * @return SubscriberInfo
502      */
503     SubscriberInfo prepareSubscriberInfo(DelegateExecution execution) {
504         def currentNSSI = execution.getVariable("currentNSSI")
505
506         String globalSubscriberId = execution.getVariable("globalSubscriberId")
507
508         String subscriberName = execution.getVariable("subscriberName")
509
510         SubscriberInfo subscriberInfo = new SubscriberInfo()
511         subscriberInfo.setGlobalSubscriberId(globalSubscriberId)
512         subscriberInfo.setSubscriberName(subscriberName)
513
514         /*
515         AAIResourcesClient client = getAAIClient()
516
517         Customer customer = null
518
519         AAIResourceUri networkServiceInstanceUri = currentNSSI['networkServiceInstanceUri']
520         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
521         Optional<Relationships> serviceSubscriptionRelationshipsOps = wrapper.getRelationships()
522         if(serviceSubscriptionRelationshipsOps.isPresent()) {
523             List<AAIResourceUri> serviceSubscriptionRelatedAAIUris = serviceSubscriptionRelationshipsOps.get().getRelatedUris(Types.SERVICE_SUBSCRIPTION)
524             if(!(serviceSubscriptionRelatedAAIUris == null || serviceSubscriptionRelatedAAIUris.isEmpty())) {
525                 AAIResourceUri serviceSubscriptionUri = serviceSubscriptionRelatedAAIUris.get(0) // Many-To-One relation
526                 Optional<ServiceSubscription> serviceSubscriptionOpt = client.get(ServiceSubscription.class, serviceSubscriptionUri)
527
528                 if(serviceSubscriptionOpt.isPresent()) {
529                     currentNSSI['serviceSubscription'] = serviceSubscriptionOpt.get()
530                 }
531
532                 wrapper = client.get(serviceSubscriptionUri)
533                 Optional<Relationships> customerRelationshipsOps = wrapper.getRelationships()
534                 if(customerRelationshipsOps.isPresent()) {
535                     List<AAIResourceUri> customerRelatedAAIUris = customerRelationshipsOps.get().getRelatedUris(Types.CUSTOMER)
536                     if(!(customerRelatedAAIUris == null || customerRelatedAAIUris.isEmpty())) {
537                         Optional<Customer> customerOpt = client.get(Customer.class, customerRelatedAAIUris.get(0)) // Many-To-One relation
538                         if(customerOpt.isPresent()) {
539                             customer = customerOpt.get()
540                             subscriberInfo.setSubscriberName(customer.getSubscriberName())
541                         }
542                     }
543                 }
544             }
545
546         } */
547
548         return subscriberInfo
549     }
550
551
552     /**
553      * Prepares Request Info
554      * @param execution
555      * @return RequestInfo
556      */
557     RequestInfo prepareRequestInfo(DelegateExecution execution, ServiceInstance networkServiceInstance) {
558         def currentNSSI = execution.getVariable("currentNSSI")
559
560         String productFamilyId = execution.getVariable("productFamilyId")
561
562         RequestInfo requestInfo = new RequestInfo()
563
564         requestInfo.setInstanceName(networkServiceInstance.getServiceInstanceName())
565         requestInfo.setSource("VID")
566         requestInfo.setProductFamilyId(productFamilyId)
567         requestInfo.setRequestorId("NBI")
568
569         return requestInfo
570     }
571
572
573     /**
574      * Prepares Model Info
575      * @param networkServiceInstance
576      * @param modelInfo
577      * @return ModelInfo
578      */
579     ModelInfo prepareServiceModelInfo(ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
580
581         ModelInfo serviceModelInfo = new ModelInfo()
582         serviceModelInfo.setModelType(ModelType.service)
583         serviceModelInfo.setModelInvariantId(networkServiceInstance.getModelInvariantId())
584
585         serviceModelInfo.setModelVersionId(modelInfo.getModelVersionId())
586         serviceModelInfo.setModelName(modelInfo.getModelName())
587         serviceModelInfo.setModelVersion(modelInfo.getModelVersion())
588
589         return serviceModelInfo
590     }
591
592
593     /**
594      * Prepares Cloud configuration
595      * @param execution
596      * @return CloudConfiguration
597      */
598     CloudConfiguration prepareCloudConfiguration(DelegateExecution execution) {
599         def currentNSSI = execution.getVariable("currentNSSI")
600
601         CloudConfiguration cloudConfiguration = new CloudConfiguration()
602
603         AAIResourcesClient client = getAAIClient()
604
605         AAIResourceUri constituteVnfUri = currentNSSI['constituteVnfUri']
606         AAIResultWrapper wrapper = client.get(constituteVnfUri)
607         Optional<Relationships> cloudRegionRelationshipsOps = wrapper.getRelationships()
608
609         if(cloudRegionRelationshipsOps.isPresent()) {
610             List<AAIResourceUri> cloudRegionRelatedAAIUris = cloudRegionRelationshipsOps.get().getRelatedUris(Types.CLOUD_REGION)
611             if (!(cloudRegionRelatedAAIUris == null || cloudRegionRelatedAAIUris.isEmpty())) {
612                 AAIResourceUri cloudRegionRelatedAAIUri = cloudRegionRelatedAAIUris.get(0)
613                 currentNSSI['cloudRegionRelatedAAIUri'] = cloudRegionRelatedAAIUri
614
615                 Optional<CloudRegion> cloudRegionrOpt = client.get(CloudRegion.class, cloudRegionRelatedAAIUris.get(0))
616                 CloudRegion cloudRegion = null
617                 if (cloudRegionrOpt.isPresent()) {
618                     cloudRegion = cloudRegionrOpt.get()
619                     cloudConfiguration.setLcpCloudRegionId(cloudRegion.getCloudRegionId())
620                     for (Tenant tenant : cloudRegion.getTenants().getTenant()) {
621                         cloudConfiguration.setTenantId(tenant.getTenantId())
622                         break // only one is required
623                     }
624
625                     cloudConfiguration.setCloudOwner(cloudRegion.getCloudOwner())
626                 }
627             }
628         }
629
630         return cloudConfiguration
631     }
632
633
634     /**
635      * Prepares a list of VF Modules
636      * @param execution
637      * @param constituteVnf
638      * @return List<VfModules>
639      */
640     List<org.onap.so.serviceinstancebeans.VfModules> prepareVfModules(DelegateExecution execution, GenericVnf constituteVnf) {
641
642         AAIResourcesClient client = getAAIClient()
643
644         List<org.onap.so.serviceinstancebeans.VfModules> vfModuless = new ArrayList<>()
645         for (VfModule vfModule : constituteVnf.getVfModules().getVfModule()) {
646             org.onap.so.serviceinstancebeans.VfModules vfmodules = new org.onap.so.serviceinstancebeans.VfModules()
647
648             ModelInfo vfModuleModelInfo = new ModelInfo()
649             vfModuleModelInfo.setModelInvariantUuid(vfModule.getModelInvariantId())
650             vfModuleModelInfo.setModelCustomizationId(vfModule.getModelCustomizationId())
651
652             AAIResourceUri vfModuleUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(vfModule.getModelInvariantId()).modelVer(vfModule.getModelVersionId()))
653
654             Optional<ModelVer> vfModuleModelVerOpt = client.get(ModelVer.class, vfModuleUrl)
655
656             if (vfModuleModelVerOpt.isPresent()) {
657                 vfModuleModelInfo.setModelVersionId(vfModuleModelVerOpt.get().getModelVersionId())
658                 vfModuleModelInfo.setModelName(vfModuleModelVerOpt.get().getModelName())
659                 vfModuleModelInfo.setModelVersion(vfModuleModelVerOpt.get().getModelVersion())
660             }
661             vfmodules.setModelInfo(vfModuleModelInfo)
662
663             vfmodules.setInstanceName(vfModule.getVfModuleName())
664
665             vfModuless.add(vfmodules)
666         }
667
668         return vfModuless
669     }
670
671
672     /**
673      * prepares VNF Model Info
674      * @param execution
675      * @param constituteVnf
676      * @return ModelInfo
677      */
678     ModelInfo prepareVNFModelInfo(DelegateExecution execution, GenericVnf constituteVnf) {
679         ModelInfo vnfModelInfo = new ModelInfo()
680
681         AAIResourcesClient client = getAAIClient()
682
683         vnfModelInfo.setModelInvariantUuid(constituteVnf.getModelInvariantId())
684         vnfModelInfo.setModelCustomizationId(constituteVnf.getModelCustomizationId())
685         vnfModelInfo.setModelInstanceName(constituteVnf.getVnfName())
686
687         AAIResourceUri vnfModelUrl = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.serviceDesignAndCreation().model(constituteVnf.getModelInvariantId()).modelVer(constituteVnf.getModelVersionId()))
688
689         Optional<ModelVer> vnfModelVerOpt = client.get(ModelVer.class, vnfModelUrl)
690
691         if (vnfModelVerOpt.isPresent()) {
692             vnfModelInfo.setModelVersionId(vnfModelVerOpt.get().getModelVersionId())
693             vnfModelInfo.setModelName(vnfModelVerOpt.get().getModelName())
694             vnfModelInfo.setModelVersion(vnfModelVerOpt.get().getModelVersion())
695         }
696
697         return vnfModelInfo
698     }
699
700
701     List<Map<String, Object>> prepareInstanceParams(DelegateExecution execution) {
702         def currentNSSI = execution.getVariable("currentNSSI")
703
704         List<Map<String, Object>> instanceParams = new ArrayList<>()
705         Map<String, Object> instanceParamsMap = new HashMap<>()
706
707         // Supported S-NSSAI
708         List<String> snssais = (List<String>) currentNSSI['S-NSSAIs']
709
710         ServiceInstance nssi = (ServiceInstance) currentNSSI['nssi']
711
712         String orchStatus = nssi.getOrchestrationStatus()
713
714
715         List<Map<String, String>> snssaiList = new ArrayList<>()
716
717         for(String snssai:snssais) {
718             Map<String, String> snssaisMap = new HashMap<>()
719             snssaisMap.put("snssai", snssai)
720             snssaisMap.put("status", orchStatus)
721             snssaiList.add(snssaisMap)
722         }
723
724         //    Map<String, List<Map<String, String>>> supportedNssaiDetails = new HashMap<>()
725         //    supportedNssaiDetails.put("sNssai", supportedNssaiDetails)
726
727         ObjectMapper mapper = new ObjectMapper()
728
729         String supportedNssaiDetailsStr = mapper.writeValueAsString(snssaiList)
730
731
732         instanceParamsMap.put("k8s-rb-profile-name", "default") // ???
733         instanceParamsMap.put("config-type", "day2") // ???
734         instanceParamsMap.put("supportedNssai", supportedNssaiDetailsStr)
735         instanceParams.add(instanceParamsMap)
736
737         return instanceParams
738     }
739
740     /**
741      * Prepares Resources
742      * @param execution
743      * @return Resources
744      */
745     Resources prepareResources(DelegateExecution execution) {
746         def currentNSSI = execution.getVariable("currentNSSI")
747
748         Resources resources = new Resources()
749
750         // VNFs
751         List<Vnfs> vnfs = new ArrayList<>()
752         // VNF
753         Vnfs vnf = new Vnfs()
754
755         // Line of Business
756         org.onap.so.serviceinstancebeans.LineOfBusiness lob = new org.onap.so.serviceinstancebeans.LineOfBusiness()
757         lob.setLineOfBusinessName("VNF")
758         vnf.setLineOfBusiness(lob)
759
760         // Product family ID
761         GenericVnf constituteVnf = (GenericVnf)currentNSSI['constituteVnf']
762         vnf.setProductFamilyId(constituteVnf.getServiceId())
763
764         // Cloud configuration
765         vnf.setCloudConfiguration(prepareCloudConfiguration(execution))
766
767         // VF Modules
768         vnf.setVfModules(prepareVfModules(execution, constituteVnf))
769
770         // Model Info
771         vnf.setModelInfo(prepareVNFModelInfo(execution, constituteVnf))
772
773         // Instance name
774         vnf.setInstanceName(constituteVnf.getVnfName())
775
776         // Instance params
777         vnf.setInstanceParams(prepareInstanceParams(execution))
778
779         // No platform data
780
781         vnfs.add(vnf)
782         resources.setVnfs(vnfs)
783
784         return resources
785     }
786
787
788     /**
789      * Prepare Service
790      * @return Service
791      */
792     org.onap.so.serviceinstancebeans.Service prepareService(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
793         org.onap.so.serviceinstancebeans.Service service = new org.onap.so.serviceinstancebeans.Service()
794
795         // Model Info
796         service.setModelInfo(prepareServiceModelInfo(networkServiceInstance, modelInfo))
797
798         service.setInstanceName(networkServiceInstance.getServiceInstanceName())
799
800         // Resources
801         service.setResources(prepareResources(execution))
802
803         return service
804
805     }
806
807
808     /**
809      * Prepares request parameters
810      * @param execution
811      * @return RequestParameters
812      */
813     RequestParameters prepareRequestParameters(DelegateExecution execution, ServiceInstance networkServiceInstance, ModelInfo modelInfo) {
814         def currentNSSI = execution.getVariable("currentNSSI")
815
816         RequestParameters requestParameters = new RequestParameters()
817
818         ServiceSubscription serviceSubscription = (ServiceSubscription)currentNSSI['serviceSubscription']
819
820         if(serviceSubscription != null) {
821             requestParameters.setSubscriptionServiceType(serviceSubscription.getServiceType())
822         }
823
824         // User params
825         List<Map<String, Object>> userParams = new ArrayList<>()
826
827         Map<String, Object> userParam = new HashMap<>()
828         userParam.put("Homing_Solution", "none")
829         userParams.add(userParam)
830
831         // Service
832         Map<String, Object> serviceMap = new HashMap<>()
833         serviceMap.put("service", prepareService(execution, networkServiceInstance, modelInfo))
834         userParams.add(serviceMap)
835         requestParameters.setUserParams(userParams)
836
837         return requestParameters
838     }
839
840
841     /**
842      * Prepare Owning Entity
843      * @param execution
844      * @return OwningEntity
845      */
846     org.onap.so.serviceinstancebeans.OwningEntity prepareOwningEntity(DelegateExecution execution) {
847         def currentNSSI = execution.getVariable("currentNSSI")
848
849         AAIResourcesClient client = getAAIClient()
850
851         AAIResourceUri networkServiceInstanceUri = (AAIResourceUri)currentNSSI['networkServiceInstanceUri']
852
853         org.onap.so.serviceinstancebeans.OwningEntity owningEntity = new org.onap.so.serviceinstancebeans.OwningEntity()
854         AAIResultWrapper wrapper = client.get(networkServiceInstanceUri)
855         Optional<Relationships> owningEntityRelationshipsOps = wrapper.getRelationships()
856         if (owningEntityRelationshipsOps.isPresent()) {
857             List<AAIResourceUri> owningEntityRelatedAAIUris = owningEntityRelationshipsOps.get().getRelatedUris(Types.OWNING_ENTITY)
858
859             if (!(owningEntityRelatedAAIUris == null || owningEntityRelatedAAIUris.isEmpty())) {
860                 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
861                 if (owningEntityOpt.isPresent()) {
862                     owningEntity.setOwningEntityId(owningEntityOpt.get().getOwningEntityId())
863                     owningEntity.setOwningEntityName(owningEntityOpt.get().getOwningEntityName())
864
865                 }
866             }
867         }
868
869         return owningEntity
870     }
871
872
873     /**
874      * Prepares Project
875      * @param execution
876      * @return Project
877      */
878     org.onap.so.serviceinstancebeans.Project prepareProject(DelegateExecution execution) {
879         def currentNSSI = execution.getVariable("currentNSSI")
880
881         AAIResourcesClient client = getAAIClient()
882
883         org.onap.so.serviceinstancebeans.Project project = new org.onap.so.serviceinstancebeans.Project()
884
885         AAIResourceUri cloudRegionRelatedAAIUri = (AAIResourceUri)currentNSSI['cloudRegionRelatedAAIUri']
886
887         if (cloudRegionRelatedAAIUri != null) {
888             AAIResultWrapper wrapper = client.get(cloudRegionRelatedAAIUri)
889             Optional<Relationships> cloudRegionOps = wrapper.getRelationships()
890             if (cloudRegionOps.isPresent()) {
891                 List<AAIResourceUri> projectAAIUris = cloudRegionOps.get().getRelatedUris(Types.PROJECT)
892                 if (!(projectAAIUris == null || projectAAIUris.isEmpty())) {
893                     Optional<org.onap.aai.domain.yang.Project> projectOpt = client.get(org.onap.aai.domain.yang.v19.Project.class, projectAAIUris.get(0))
894                     if (projectOpt.isPresent()) {
895                         project.setProjectName(projectOpt.get().getProjectName())
896                     }
897                 }
898             }
899         }
900
901         return project
902     }
903
904
905     /**
906      * Prepares RequestDetails object
907      * @param execution
908      * @return
909      */
910     String prepareRequestDetails(DelegateExecution execution) {
911         String errorCode = ""
912         String errorMessage = ""
913         String response
914
915         RequestDetails requestDetails = new RequestDetails()
916
917         def currentNSSI = execution.getVariable("currentNSSI")
918
919         ServiceInstance networkServiceInstance = (ServiceInstance)currentNSSI['networkServiceInstance']
920
921         try {
922             // Model Info
923             ModelInfo modelInfo = prepareModelInfo(execution)
924             requestDetails.setModelInfo(modelInfo)
925
926             // Subscriber Info
927             requestDetails.setSubscriberInfo(prepareSubscriberInfo(execution))
928
929             // Request Info
930             requestDetails.setRequestInfo(prepareRequestInfo(execution, networkServiceInstance))
931
932             // Request Parameters
933             requestDetails.setRequestParameters(prepareRequestParameters(execution, networkServiceInstance, modelInfo))
934
935             // Cloud configuration
936             requestDetails.setCloudConfiguration(prepareCloudConfiguration(execution))
937
938             // Owning entity
939             requestDetails.setOwningEntity(prepareOwningEntity(execution))
940
941             // Project
942             requestDetails.setProject(prepareProject(execution))
943
944             ObjectMapper mapper = new ObjectMapper()
945
946             response = mapper.writeValueAsString(requestDetails)
947         }
948         catch (any) {
949             String msg = "Exception in ${getPrefix()}.prepareRequestDetails. " + any.getCause()
950             LOGGER.error(msg)
951
952             response =  "{\n" +
953                     " \"errorCode\": \"7000\",\n" +
954                     " \"errorMessage\": \"${msg}\"\n" +
955                     "}"
956
957         }
958
959         return response
960     }
961
962
963     String getAuthHeader(DelegateExecution execution, String basicAuthValue, String msokey) {
964         String response = ""
965         String errorCode = ""
966         String errorMessage = ""
967
968         LOGGER.debug("Obtained BasicAuth username and password for OOF: " + basicAuthValue)
969         try {
970             response = utils.getBasicAuth(basicAuthValue, msokey)
971         } catch (Exception ex) {
972             LOGGER.error("Unable to encode username and password string: ", ex)
973
974             errorCode = "401"
975             errorMessage = "Internal Error - Unable to encode username and password string"
976
977             response =  "{\n" +
978                     " \"errorCode\": \"${errorCode}\",\n" +
979                     " \"errorMessage\": \"${errorMessage}\"\n" +
980                     "}"
981         }
982
983         return response
984     }
985
986
987     String encryptBasicAuth(String basicAuth, String msoKey) {
988         return utils.encrypt(basicAuth, msoKey)
989     }
990
991
992     /**
993      * Removes Slice Profile association with NSSI
994      * @param execution
995      */
996     void removeSPAssociationWithNSSI(DelegateExecution execution) {
997         LOGGER.trace("${getPrefix()} Start removeSPAssociationWithNSSI")
998
999         AAIResourcesClient client = getAAIClient()
1000
1001         def currentNSSI = execution.getVariable("currentNSSI")
1002
1003         String nssiId = currentNSSI['nssiId']
1004         AAIResourceUri nssiUri = AAIUriFactory.createResourceUri(Types.SERVICE_INSTANCE.getFragment(nssiId))
1005
1006         AAIResourceUri sliceProfileInstanceUri = (AAIResourceUri)currentNSSI['sliceProfileInstanceUri']
1007
1008         Optional<ServiceInstance> sliceProfileInstanceOpt = client.get(ServiceInstance.class, sliceProfileInstanceUri)
1009         if (sliceProfileInstanceOpt.isPresent()) {
1010             ServiceInstance sliceProfileInstance = sliceProfileInstanceOpt.get()
1011
1012             List<SliceProfile> associatedProfiles = sliceProfileInstance.getSliceProfiles()?.getSliceProfile()
1013
1014             String currentSNSSAI = currentNSSI['S-NSSAI']
1015
1016             if(!(associatedProfiles == null || associatedProfiles.isEmpty())) {
1017                 // Removes slice profile which contains given S-NSSAI and  updates Slice Profile Instance
1018                 associatedProfiles.removeIf({ associatedProfile -> (associatedProfile.getSNssai().equals(currentSNSSAI)) })
1019
1020                 try {
1021                     client.update(sliceProfileInstanceUri, sliceProfileInstance)
1022
1023                     currentNSSI['sliceProfileInstance'] = sliceProfileInstance
1024                 } catch (Exception e) {
1025                     exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile association with NSSI update call: " + e.getMessage())
1026                 }
1027             }
1028             else {
1029                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No slice profiles found")
1030             }
1031
1032         }
1033         else {
1034             exceptionUtil.buildAndThrowWorkflowException(execution, 500, "No slice profile instance found")
1035         }
1036
1037         // Removes SLice Profile Instance association with NSSI
1038         try {
1039             client.disconnect(nssiUri, sliceProfileInstanceUri)
1040         }
1041         catch (Exception e) {
1042             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance association with NSSI dosconnect call: " + e.getMessage())
1043         }
1044
1045
1046         LOGGER.trace("${getPrefix()} Exit removeSPAssociationWithNSSI")
1047     }
1048
1049
1050     /**
1051      * Deletes Slice Profile Instance
1052      * @param execution
1053      */
1054     void deleteSliceProfileInstance(DelegateExecution execution) {
1055         LOGGER.trace("${getPrefix()} Start deleteSliceProfileInstance")
1056
1057         AAIResourcesClient client = getAAIClient()
1058
1059         def currentNSSI = execution.getVariable("currentNSSI")
1060
1061         AAIResourceUri sliceProfileInstanceURI = (AAIResourceUri)currentNSSI['sliceProfileInstanceUri']
1062
1063         try {
1064             client.delete(sliceProfileInstanceURI)
1065         }catch(Exception e){
1066             exceptionUtil.buildAndThrowWorkflowException(execution, 25000, "Exception occured while Slice Profile Instance delete call: " + e.getMessage())
1067         }
1068
1069         LOGGER.trace("${getPrefix()} Exit deleteSliceProfileInstance")
1070     }
1071
1072
1073     /**
1074      * Prepares update resource operation status
1075      * @param execution
1076      */
1077     void prepareUpdateResourceOperationStatus(DelegateExecution execution) {
1078         LOGGER.trace("${getPrefix()} Start updateServiceOperationStatus")
1079
1080         def currentNSSI = execution.getVariable("currentNSSI")
1081
1082         //Prepare Update Status for PUT failure and success
1083         String isTimeOutVar = execution.getVariable("isTimeOut")
1084         if(!isBlank(isTimeOutVar) && isTimeOutVar.equals("YES")) {
1085             LOGGER.error("TIMEOUT - SO PUT Failure")
1086             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "SO PUT Failure")
1087         } else {
1088             execution.setVariable("progress", "100")
1089             execution.setVariable("status", "finished")
1090             execution.setVariable("operationContent", "${getAction()} Core NSSI successful.")
1091         }
1092
1093         setResourceOperationStatus(execution, "finished", "100", "Core NSSI ${getAction()} successful")
1094
1095         LOGGER.trace("${getPrefix()} Exit updateServiceOperationStatus")
1096     }
1097
1098
1099     /**
1100      * Prepares ResourceOperation status
1101      * @param execution
1102      * @param operationType
1103      */
1104     void setResourceOperationStatus(DelegateExecution execution, String status, String progress, String statusDesc) {
1105         LOGGER.trace("${getPrefix()} Start setResourceOperationStatus")
1106
1107         def currentNSSI = execution.getVariable("currentNSSI")
1108
1109         String serviceId = currentNSSI['nssiId']
1110         String jobId = execution.getVariable("jobId")
1111         String nsiId = currentNSSI['nsiId']
1112         String operationType = execution.getVariable("operationType")
1113
1114         ResourceOperationStatus resourceOperationStatus = new ResourceOperationStatus()
1115         resourceOperationStatus.setServiceId(serviceId)
1116         resourceOperationStatus.setOperationId(jobId)
1117         resourceOperationStatus.setResourceTemplateUUID(nsiId)
1118         resourceOperationStatus.setOperType(operationType)
1119         resourceOperationStatus.setStatus(status)
1120         resourceOperationStatus.setProgress(progress)
1121         resourceOperationStatus.setStatusDescription(statusDesc)
1122         requestDBUtil.prepareUpdateResourceOperationStatus(execution, resourceOperationStatus)
1123
1124         LOGGER.trace("${getPrefix()} Exit setResourceOperationStatus")
1125     }
1126
1127
1128     /**
1129      * Prepares failed operation status update
1130      * @param execution
1131      */
1132     void prepareFailedOperationStatusUpdate(DelegateExecution execution) {
1133         LOGGER.trace("${getPrefix()} Start prepareFailedOperationStatusUpdate")
1134
1135         setResourceOperationStatus(execution, "failed", "0", "Core NSSI ${getAction()} Failed")
1136
1137         LOGGER.trace("${getPrefix()} Exit prepareFailedOperationStatusUpdate")
1138     }
1139
1140
1141     /**
1142      * Gets progress status of ServiceInstance PUT operation
1143      * @param execution
1144      */
1145     public void getPUTServiceInstanceProgress(DelegateExecution execution) {
1146         LOGGER.trace("${getPrefix()} Start getPUTServiceInstanceProgress")
1147
1148         def currentNSSI = execution.getVariable("currentNSSI")
1149
1150         String url = currentNSSI['putServiceInstanceURL']
1151
1152         getProgress(execution, url, "putStatus")
1153
1154         LOGGER.trace("${getPrefix()} Exit getPUTServiceInstanceProgress")
1155     }
1156
1157
1158     void getProgress(DelegateExecution execution, String url, String statusVariableName) {
1159         String msg=""
1160         try {
1161
1162             ExternalAPIUtil externalAPIUtil = getExternalAPIUtilFactory().create()
1163             Response response = externalAPIUtil.executeExternalAPIGetCall(execution, url)
1164             int responseCode = response.getStatus()
1165             execution.setVariable("GetServiceOrderResponseCode", responseCode)
1166             LOGGER.debug("Get ServiceOrder response code is: " + responseCode)
1167
1168             String extApiResponse = response.readEntity(String.class)
1169             JSONObject responseObj = new JSONObject(extApiResponse)
1170             execution.setVariable("GetServiceOrderResponse", extApiResponse)
1171             LOGGER.debug("Create response body is: " + extApiResponse)
1172             //Process Response //200 OK 201 CREATED 202 ACCEPTED
1173             if(responseCode == 200 || responseCode == 201 || responseCode == 202 )
1174             {
1175                 LOGGER.debug("Get Create ServiceOrder Received a Good Response")
1176                 String orderState = responseObj.get("state")
1177                 if("REJECTED".equalsIgnoreCase(orderState)) {
1178                     prepareFailedOperationStatusUpdate(execution)
1179                     return
1180                 }
1181
1182                 JSONArray items = responseObj.getJSONArray("orderItem")
1183                 JSONObject item = items.get(0)
1184                 JSONObject service = item.get("service")
1185                 String networkServiceId = service.get("id")
1186                 if (networkServiceId == null || networkServiceId.equals("null")) {
1187                     prepareFailedOperationStatusUpdate(execution)
1188                     return
1189                 }
1190
1191                 execution.setVariable("networkServiceId", networkServiceId)
1192                 String serviceOrderState = item.get("state")
1193                 execution.setVariable("ServiceOrderState", serviceOrderState)
1194                 // Get serviceOrder State and process progress
1195                 if("ACKNOWLEDGED".equalsIgnoreCase(serviceOrderState)) {
1196                     execution.setVariable(statusVariableName, "processing")
1197                 }
1198                 else if("INPROGRESS".equalsIgnoreCase(serviceOrderState)) {
1199                     execution.setVariable(statusVariableName, "processing")
1200                 }
1201                 else if("COMPLETED".equalsIgnoreCase(serviceOrderState)) {
1202                     execution.setVariable(statusVariableName, "completed")
1203                 }
1204                 else if("FAILED".equalsIgnoreCase(serviceOrderState)) {
1205                     msg = "ServiceOrder failed"
1206                     exceptionUtil.buildAndThrowWorkflowException(execution, 7000,  msg)
1207                 }
1208                 else {
1209                     msg = "ServiceOrder failed"
1210                     exceptionUtil.buildAndThrowWorkflowException(execution, 7000,  msg)
1211                 }
1212             }
1213             else{
1214                 msg = "Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode
1215                 prepareFailedOperationStatusUpdate(execution)
1216             }
1217
1218         }catch(Exception e){
1219             exceptionUtil.buildAndThrowWorkflowException(execution, 7000,  e.getMessage())
1220         }
1221
1222     }
1223
1224
1225
1226     /**
1227      * Delays 5 sec
1228      * @param execution
1229      */
1230     void timeDelay(DelegateExecution execution) {
1231         LOGGER.trace("${getPrefix()} Start timeDelay")
1232
1233         try {
1234             LOGGER.debug("${getPrefix()} timeDelay going to sleep for 5 sec")
1235
1236             Thread.sleep(5000)
1237
1238             LOGGER.debug("${getPrefix()} ::: timeDelay wakeup after 5 sec")
1239         } catch(InterruptedException e) {
1240             LOGGER.error("${getPrefix()} ::: timeDelay exception" + e)
1241         }
1242
1243         LOGGER.trace("${getPrefix()} Exit timeDelay")
1244     }
1245
1246
1247     /**
1248      * Returns AAI client
1249      * @return AAI client
1250      */
1251     AAIResourcesClient getAAIClient() {
1252         return new AAIResourcesClient()
1253     }
1254
1255
1256     ExternalAPIUtilFactory getExternalAPIUtilFactory() {
1257         return new ExternalAPIUtilFactory()
1258     }
1259
1260
1261     String getPrefix() {
1262         return PREFIX
1263     }
1264
1265     String getAction() {
1266         return ""
1267     }
1268 }