Merge "Sonar fixes"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoCreateVFCNetworkServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - SO
4  * ================================================================================
5  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.scripts
24
25 import org.onap.so.logger.LoggingAnchor
26 import org.onap.so.client.HttpClientFactory
27 import org.onap.aaiclient.client.aai.AAIObjectType
28 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
29 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
30 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder
31 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types
32 import org.camunda.bpm.engine.delegate.BpmnError
33 import org.camunda.bpm.engine.delegate.DelegateExecution
34 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
35 import org.onap.so.bpmn.common.scripts.ExceptionUtil
36 import org.onap.so.bpmn.core.json.JsonUtils
37 import org.onap.so.client.HttpClient
38 import org.onap.logging.filter.base.ErrorCode
39 import org.onap.so.logger.MessageEnum
40 import org.slf4j.Logger
41 import org.slf4j.LoggerFactory
42 import org.onap.so.bpmn.core.UrnPropertiesReader
43
44 import org.onap.logging.filter.base.ONAPComponents;
45
46 import javax.ws.rs.core.Response
47
48 /**
49  * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process.
50  * flow for VFC Network Service Create
51  */
52 public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProcessor {
53     private static final Logger logger = LoggerFactory.getLogger( DoCreateVFCNetworkServiceInstance.class);
54
55
56     ExceptionUtil exceptionUtil = new ExceptionUtil()
57
58     JsonUtils jsonUtil = new JsonUtils()
59
60     /**
61      * Pre Process the BPMN Flow Request
62      * Inclouds:
63      * generate the nsOperationKey
64      * generate the nsParameters
65      */
66     void preProcessRequest (DelegateExecution execution) {
67        String msg = ""
68        logger.trace("preProcessRequest()")
69        try {
70            //deal with nsName and Description
71            String nsServiceName = execution.getVariable("nsServiceName")
72            String nsServiceDescription = execution.getVariable("nsServiceDescription")
73            logger.debug("nsServiceName:" + nsServiceName + " nsServiceDescription:" + nsServiceDescription)
74            //deal with operation key
75            String globalSubscriberId = execution.getVariable("globalSubscriberId")
76            logger.debug("globalSubscriberId:" + globalSubscriberId)
77            String serviceType = execution.getVariable("serviceType")
78            logger.debug("serviceType:" + serviceType)
79            String serviceId = execution.getVariable("serviceId")
80            logger.debug("serviceId:" + serviceId)
81            String operationId = execution.getVariable("operationId")
82            logger.debug("serviceType:" + serviceType)
83            String nodeTemplateUUID = execution.getVariable("resourceUUID")
84            logger.debug("nodeTemplateUUID:" + nodeTemplateUUID)
85            /*
86             * segmentInformation needed as a object of segment
87             * {
88             *     "domain":"",
89             *     "nodeTemplateName":"",
90             *     "nodeType":"",
91             *     "nsParameters":{
92             *       //this is the nsParameters sent to VF-C
93             *     }
94             * }
95             */
96            String nsParameters = execution.getVariable("resourceParameters")
97            logger.debug("nsParameters:" + nsParameters)
98            String nsOperationKey = """{
99                    "globalSubscriberId":"${globalSubscriberId}",
100                    "serviceType":"${serviceType}",
101                    "serviceId":"${serviceId}",
102                    "operationId":"${operationId}",
103                    "nodeTemplateUUID":"${nodeTemplateUUID}"
104                     }"""
105            execution.setVariable("nsOperationKey", nsOperationKey);
106            execution.setVariable("nsParameters", nsParameters)
107
108            String vfcAdapterUrl = UrnPropertiesReader.getVariable("mso.adapters.vfc.rest.endpoint", execution)
109                    
110            if (vfcAdapterUrl == null || vfcAdapterUrl.isEmpty()) {
111                msg = getProcessKey(execution) + ': mso:adapters:vfcc:rest:endpoint URN mapping is not defined'
112                logger.debug(msg)
113            }
114
115            while (vfcAdapterUrl.endsWith('/')) {
116                vfcAdapterUrl = vfcAdapterUrl.substring(0, vfcAdapterUrl.length()-1)
117            }
118                    
119            execution.setVariable("vfcAdapterUrl", vfcAdapterUrl)
120
121
122        } catch (BpmnError e) {
123            throw e;
124        } catch (Exception ex){
125            msg = "Exception in preProcessRequest " + ex.getMessage()
126            logger.debug(msg)
127            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
128        }
129        logger.trace("Exit preProcessRequest")
130         }
131
132     /**
133      * create NS task
134      */
135     void createNetworkService(DelegateExecution execution) {
136         logger.trace("createNetworkService")
137         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
138         String nsOperationKey = execution.getVariable("nsOperationKey");
139         String nsParameters = execution.getVariable("nsParameters");
140         String nsServiceName = execution.getVariable("nsServiceName")
141         String nsServiceDescription = execution.getVariable("nsServiceDescription")
142         String reqBody ="""{
143                 "nsServiceName":"${nsServiceName}",
144                 "nsServiceDescription":"${nsServiceDescription}",
145                 "nsOperationKey":${nsOperationKey},
146                 "nsParameters":${nsParameters}
147                }"""
148         Response apiResponse = postRequest(execution, vfcAdapterUrl + "/ns", reqBody)
149         String returnCode = apiResponse.getStatus()
150         String aaiResponseAsString = apiResponse.readEntity(String.class)
151         String nsInstanceId = "";
152         if(returnCode== "200" || returnCode == "201"){
153             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")
154         }
155         execution.setVariable("nsInstanceId", nsInstanceId)
156         logger.trace("Exit  createNetworkService")
157     }
158
159     /**
160      * instantiate NS task
161      */
162     void instantiateNetworkService(DelegateExecution execution) {
163         logger.trace("instantiateNetworkService")
164         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
165         String nsOperationKey = execution.getVariable("nsOperationKey");
166         String nsParameters = execution.getVariable("nsParameters");
167         String nsServiceName = execution.getVariable("nsServiceName")
168         String nsServiceDescription = execution.getVariable("nsServiceDescription")
169         String reqBody ="""{
170         "nsServiceName":"${nsServiceName}",
171         "nsServiceDescription":"${nsServiceDescription}",
172         "nsOperationKey":${nsOperationKey},
173         "nsParameters":${nsParameters}
174        }"""
175         String nsInstanceId = execution.getVariable("nsInstanceId")
176         String url = vfcAdapterUrl + "/ns/" +nsInstanceId + "/instantiate"
177         Response apiResponse = postRequest(execution, url, reqBody)
178         String returnCode = apiResponse.getStatus()
179         String aaiResponseAsString = apiResponse.readEntity(String.class)
180         String jobId = "";
181         if(returnCode== "200"|| returnCode == "201"){
182             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
183         }
184         execution.setVariable("jobId", jobId)
185         logger.trace("Exit  instantiateNetworkService")
186     }
187
188     /**
189      * query NS task
190      */
191     void queryNSProgress(DelegateExecution execution) {
192         logger.trace("queryNSProgress")
193         String vfcAdapterUrl = execution.getVariable("vfcAdapterUrl")
194         String jobId = execution.getVariable("jobId")
195         String nsOperationKey = execution.getVariable("nsOperationKey");
196         String url = vfcAdapterUrl + "/jobs/" + jobId
197         Response apiResponse = postRequest(execution, url, nsOperationKey)
198         String returnCode = apiResponse.getStatus()
199         String aaiResponseAsString = apiResponse.readEntity(String.class)
200         String operationStatus = "error"
201         if(returnCode== "200"|| returnCode == "201"){
202             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
203         }
204         execution.setVariable("operationStatus", operationStatus)
205         logger.trace("Exit  queryNSProgress")
206     }
207
208     /**
209      * delay 5 sec
210      */
211     void timeDelay(DelegateExecution execution) {
212         try {
213             Thread.sleep(5000);
214         } catch(InterruptedException e) {
215            logger.debug("Time Delay exception" + e )
216         }
217     }
218
219     /**
220      * finish NS task
221      */
222     void addNSRelationship(DelegateExecution execution) {
223         logger.trace("addNSRelationship")
224         String nsInstanceId = execution.getVariable("nsInstanceId")
225         if(nsInstanceId == null || nsInstanceId == ""){
226             logger.debug(" create NS failed, so do not need to add relationship")
227             return
228         }
229         String globalSubscriberId = execution.getVariable("globalSubscriberId")
230         String serviceType = execution.getVariable("serviceType")
231         String serviceId = execution.getVariable("serviceId")
232
233         AAIResourceUri nsUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(serviceType).serviceInstance(nsInstanceId))
234         AAIResourceUri relatedServiceUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.business().customer(globalSubscriberId).serviceSubscription(serviceType).serviceInstance(serviceId))
235
236         try{
237             getAAIClient().connect(nsUri,relatedServiceUri)
238             logger.info("NS relationship to Service added successfully")
239         }catch(Exception e){
240             logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
241                     "Exception occured while executing AAI Put Call", "BPMN",
242                     ErrorCode.UnknownError.getValue(), "Exception is:\n" + e);
243             throw new BpmnError("MSOWorkflowException")
244         }
245     }
246
247     /**
248      * post request
249      * url: the url of the request
250      * requestBody: the body of the request
251      */
252     private Response postRequest(DelegateExecution execution, String urlString, String requestBody){
253         logger.trace("Started Execute VFC adapter Post Process")
254         logger.debug("url:"+urlString +"\nrequestBody:"+ requestBody)
255         Response apiResponse = null
256         try{
257
258                         URL url = new URL(urlString);
259             
260             // Get the Basic Auth credentials for the VFCAdapter, username is 'bpel', auth is '07a7159d3bf51a0e53be7a8f89699be7'
261             // user 'bepl' authHeader is the same with mso.db.auth
262             String basicAuthValuedb =  UrnPropertiesReader.getVariable("mso.db.auth", execution)
263             HttpClient httpClient = new HttpClientFactory().newJsonClient(url, ONAPComponents.VNF_ADAPTER)
264             httpClient.addAdditionalHeader("Accept", "application/json")
265             httpClient.addAdditionalHeader("Authorization", basicAuthValuedb)
266
267             apiResponse = httpClient.post(requestBody)
268
269             logger.debug("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class))
270             logger.trace("Completed Execute VF-C adapter Post Process")
271         }catch(Exception e){
272                         logger.error("Exception occured while executing VFC Adapter Post Call"  + e.getMessage ());
273             throw new BpmnError("MSOWorkflowException")
274         }
275         return apiResponse
276     }
277 }