Adding Junit
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / CreateVFCNSResource.groovy
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * OPENECOMP - SO\r
4  * ================================================================================\r
5  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.\r
6  * ================================================================================\r
7  * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * you may not use this file except in compliance with the License.\r
9  * You may obtain a copy of the License at\r
10  * \r
11  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * \r
13  * Unless required by applicable law or agreed to in writing, software\r
14  * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * See the License for the specific language governing permissions and\r
17  * limitations under the License.\r
18  * ============LICENSE_END=========================================================\r
19  */\r
20 \r
21 package org.openecomp.mso.bpmn.infrastructure.scripts;\r
22 \r
23 import static org.apache.commons.lang3.StringUtils.*;\r
24 import groovy.xml.XmlUtil\r
25 import groovy.json.*\r
26 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor \r
27 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil \r
28 import org.openecomp.mso.bpmn.core.WorkflowException \r
29 import org.openecomp.mso.bpmn.core.json.JsonUtils \r
30 import org.openecomp.mso.rest.APIResponse\r
31 \r
32 import java.util.UUID;\r
33 \r
34 import org.camunda.bpm.engine.delegate.BpmnError \r
35 import org.camunda.bpm.engine.delegate.DelegateExecution\r
36 import org.apache.commons.lang3.*\r
37 import org.apache.commons.codec.binary.Base64;\r
38 import org.springframework.web.util.UriUtils \r
39 import org.openecomp.mso.rest.RESTClient \r
40 import org.openecomp.mso.rest.RESTConfig\r
41 import org.openecomp.mso.rest.APIResponse;\r
42 \r
43 /**\r
44  * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process.\r
45  * flow for VFC Network Service Create\r
46  */\r
47 public class CreateVFCNSResource extends AbstractServiceTaskProcessor {\r
48 \r
49     String vfcUrl = "/vfc/rest/v1/vfcadapter"\r
50             \r
51     String host = "http://mso.mso.testlab.openecomp.org:8080"\r
52     \r
53     ExceptionUtil exceptionUtil = new ExceptionUtil()\r
54 \r
55     JsonUtils jsonUtil = new JsonUtils()\r
56 \r
57     /**\r
58      * CreateVFCNSResource\r
59      * Pre Process the BPMN Flow Request\r
60      * Inclouds:\r
61      * generate the nsOperationKey\r
62      * generate the nsParameters\r
63      */\r
64     public void preProcessRequest (DelegateExecution execution) {\r
65            def isDebugEnabled=execution.getVariable("isDebugLogEnabled")\r
66        String msg = ""\r
67        utils.log("INFO", " *** preProcessRequest() *** ", isDebugEnabled)\r
68        try {\r
69            //deal with nsName and Description\r
70            String nsServiceName = execution.getVariable("nsServiceName")\r
71            String nsServiceDescription = execution.getVariable("nsServiceDescription")\r
72            utils.log("INFO", "nsServiceName:" + nsServiceName + " nsServiceDescription:" + nsServiceDescription, isDebugEnabled)\r
73            //deal with operation key\r
74            String globalSubscriberId = execution.getVariable("globalSubscriberId")\r
75            utils.log("INFO", "globalSubscriberId:" + globalSubscriberId, isDebugEnabled)\r
76            String serviceType = execution.getVariable("serviceType")\r
77            utils.log("INFO", "serviceType:" + serviceType, isDebugEnabled)\r
78            String serviceId = execution.getVariable("serviceId")\r
79            utils.log("INFO", "serviceId:" + serviceId, isDebugEnabled)\r
80            String operationId = execution.getVariable("operationId")\r
81            utils.log("INFO", "serviceType:" + serviceType, isDebugEnabled)\r
82            String nodeTemplateUUID = execution.getVariable("resourceUUID")\r
83            utils.log("INFO", "nodeTemplateUUID:" + nodeTemplateUUID, isDebugEnabled)\r
84            /*\r
85             * segmentInformation needed as a object of segment\r
86             * {\r
87             *     "domain":"",\r
88             *     "nodeTemplateName":"",\r
89             *     "nodeType":"",\r
90             *     "nsParameters":{\r
91             *       //this is the nsParameters sent to VF-C\r
92             *     }\r
93             * }\r
94             */\r
95            String nsParameters = execution.getVariable("resourceParameters")\r
96            utils.log("INFO", "nsParameters:" + nsParameters, isDebugEnabled)\r
97            String nsOperationKey = """{\r
98                    "globalSubscriberId":"${globalSubscriberId}",\r
99                    "serviceType":"${serviceType}",\r
100                    "serviceId":"${serviceId}",\r
101                    "operationId":"${operationId}",\r
102                    "nodeTemplateUUID":"${nodeTemplateUUID}"\r
103                     }"""\r
104            execution.setVariable("nsOperationKey", nsOperationKey);\r
105            execution.setVariable("nsParameters", nsParameters)\r
106            \r
107 \r
108        } catch (BpmnError e) {\r
109            throw e;\r
110        } catch (Exception ex){\r
111            msg = "Exception in preProcessRequest " + ex.getMessage()\r
112            utils.log("INFO", msg, isDebugEnabled)\r
113            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)\r
114        }\r
115        utils.log("INFO"," ***** Exit preProcessRequest *****",  isDebugEnabled)\r
116         }\r
117 \r
118     /**\r
119      * create NS task\r
120      */\r
121     public void createNetworkService(DelegateExecution execution) {\r
122         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")\r
123         utils.log("INFO"," *****  createNetworkService *****",  isDebugEnabled)\r
124         String nsOperationKey = execution.getVariable("nsOperationKey");\r
125         String nsParameters = execution.getVariable("nsParameters");\r
126         String nsServiceName = execution.getVariable("nsServiceName")\r
127         String nsServiceDescription = execution.getVariable("nsServiceDescription")\r
128         String reqBody ="""{\r
129                 "nsServiceName":"${nsServiceName}",\r
130                 "nsServiceDescription":"${nsServiceDescription}",\r
131                 "nsOperationKey":${nsOperationKey},\r
132                 "nsParameters":${nsParameters}\r
133                }"""\r
134         APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody)\r
135         String returnCode = apiResponse.getStatusCode()\r
136         String aaiResponseAsString = apiResponse.getResponseBodyAsString()\r
137         String nsInstanceId = "";\r
138         if(returnCode== "200" || returnCode == "201"){\r
139             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")\r
140         }\r
141         execution.setVariable("nsInstanceId", nsInstanceId)\r
142         utils.log("INFO"," *****Exit  createNetworkService *****",  isDebugEnabled)\r
143     }\r
144 \r
145     /**\r
146      * instantiate NS task\r
147      */\r
148     public void instantiateNetworkService(DelegateExecution execution) {\r
149         def isDebugEnabled= execution.getVariable("isDebugLogEnabled")\r
150         utils.log("INFO"," *****  instantiateNetworkService *****",  isDebugEnabled)\r
151         String nsOperationKey = execution.getVariable("nsOperationKey");\r
152         String nsParameters = execution.getVariable("nsParameters");\r
153         String nsServiceName = execution.getVariable("nsServiceName")\r
154         String nsServiceDescription = execution.getVariable("nsServiceDescription")\r
155         String reqBody ="""{\r
156         "nsServiceName":"${nsServiceName}",\r
157         "nsServiceDescription":"${nsServiceDescription}",\r
158         "nsOperationKey":${nsOperationKey},\r
159         "nsParameters":${nsParameters}\r
160        }"""\r
161         String nsInstanceId = execution.getVariable("nsInstanceId")\r
162         String url = host + vfcUrl + "/ns/" +nsInstanceId + "/instantiate"\r
163         APIResponse apiResponse = postRequest(execution, url, reqBody)\r
164         String returnCode = apiResponse.getStatusCode()\r
165         String aaiResponseAsString = apiResponse.getResponseBodyAsString()\r
166         String jobId = "";\r
167         if(returnCode== "200"|| returnCode == "201"){\r
168             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")\r
169         }\r
170         execution.setVariable("jobId", jobId)\r
171         utils.log("INFO"," *****Exit  instantiateNetworkService *****",  isDebugEnabled)\r
172     }\r
173 \r
174     /**\r
175      * query NS task\r
176      */\r
177     public void queryNSProgress(DelegateExecution execution) {\r
178         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")\r
179         utils.log("INFO"," *****  queryNSProgress *****",  isDebugEnabled)\r
180         String jobId = execution.getVariable("jobId")\r
181         String nsOperationKey = execution.getVariable("nsOperationKey");\r
182         String url = host + vfcUrl + "/jobs/" + jobId\r
183         APIResponse apiResponse = postRequest(execution, url, nsOperationKey)\r
184         String returnCode = apiResponse.getStatusCode()\r
185         String aaiResponseAsString = apiResponse.getResponseBodyAsString()\r
186         String operationStatus = "error"\r
187         if(returnCode== "200"|| returnCode == "201"){\r
188             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")\r
189         }\r
190         execution.setVariable("operationStatus", operationStatus)\r
191         utils.log("INFO"," *****Exit  queryNSProgress *****",  isDebugEnabled)\r
192     }\r
193 \r
194     /**\r
195      * delay 5 sec \r
196      */\r
197     public void timeDelay(DelegateExecution execution) {\r
198         def isDebugEnabled= execution.getVariable("isDebugLogEnabled")\r
199         try {\r
200             Thread.sleep(5000);\r
201         } catch(InterruptedException e) {           \r
202             utils.log("ERROR", "Time Delay exception" + e , isDebugEnabled)\r
203         }\r
204     }\r
205 \r
206     /**\r
207      * finish NS task\r
208      */\r
209     public void addNSRelationship(DelegateExecution execution) {\r
210         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")\r
211         utils.log("INFO"," ***** addNSRelationship *****",  isDebugEnabled)\r
212         String nsInstanceId = execution.getVariable("nsInstanceId")\r
213         if(nsInstanceId == null || nsInstanceId == ""){\r
214             utils.log("INFO"," create NS failed, so do not need to add relationship",  isDebugEnabled)\r
215             return\r
216         }\r
217         String globalSubscriberId = execution.getVariable("globalSubscriberId")\r
218         String serviceType = execution.getVariable("serviceType")\r
219         String serviceId = execution.getVariable("serviceId")\r
220         String addRelationPayload = """<relationship xmlns="http://org.openecomp.aai.inventory/v11">\r
221                                             <related-to>service-instance</related-to>\r
222                                             <related-link>/aai/v11/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${nsInstanceId}</related-link>\r
223                                             <relationship-data>\r
224                                                 <relationship-key>customer.global-customer-id</relationship-key>\r
225                                                 <relationship-value>${globalSubscriberId}</relationship-value>\r
226                                             </relationship-data>\r
227                                             <relationship-data>\r
228                                                 <relationship-key>service-subscription.service-type</relationship-key>\r
229                                                 <relationship-value>${serviceType}</relationship-value>\r
230                                             </relationship-data>\r
231                                            <relationship-data>\r
232                                                 <relationship-key>service-instance.service-instance-id</relationship-key>\r
233                                                 <relationship-value>${nsInstanceId}</relationship-value>\r
234                                             </relationship-data>           \r
235                                         </relationship>"""\r
236         String endpoint = execution.getVariable("URN_aai_endpoint")  \r
237         utils.log("INFO","Add Relationship req:\n" + addRelationPayload,  isDebugEnabled)\r
238         String url = endpoint + "/aai/v11/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId + "/relationship-list/relationship"\r
239         APIResponse aaiRsp = executeAAIPutCall(execution, url, addRelationPayload)\r
240         utils.log("INFO","aai response status code:" + aaiRsp.getStatusCode(),  isDebugEnabled)\r
241         utils.log("INFO","aai response content:" + aaiRsp.getResponseBodyAsString(),  isDebugEnabled)\r
242         utils.log("INFO"," *****Exit addNSRelationship *****",  isDebugEnabled)\r
243     }\r
244     \r
245     public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){\r
246         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")\r
247         utils.log("INFO", " ======== Started Execute AAI Put Process ======== ",  isDebugEnabled) \r
248         APIResponse apiResponse = null\r
249         try{\r
250             String uuid = utils.getRequestID()\r
251             utils.log("INFO","Generated uuid is: " + uuid,  isDebugEnabled) \r
252             utils.log("INFO","URL to be used is: " + url,  isDebugEnabled) \r
253             String userName = execution.getVariable("URN_aai_auth")\r
254             String password = execution.getVariable("URN_mso_msoKey")\r
255             String basicAuthCred = utils.getBasicAuth(userName,password)\r
256             RESTConfig config = new RESTConfig(url);\r
257             RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml");\r
258             if (basicAuthCred != null && !"".equals(basicAuthCred)) {\r
259                 client.addAuthorizationHeader(basicAuthCred)\r
260             }\r
261             apiResponse = client.httpPut(payload)\r
262             utils.log("INFO","======== Completed Execute AAI Put Process ======== ",  isDebugEnabled) \r
263         }catch(Exception e){\r
264             utils.log("ERROR","Exception occured while executing AAI Put Call. Exception is: \n" + e,  isDebugEnabled) \r
265             throw new BpmnError("MSOWorkflowException")\r
266         }\r
267         return apiResponse\r
268     }\r
269 \r
270     /**\r
271      * post request\r
272      * url: the url of the request\r
273      * requestBody: the body of the request\r
274      */\r
275     private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){\r
276         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")\r
277         utils.log("INFO"," ***** Started Execute VFC adapter Post Process *****",  isDebugEnabled)\r
278         utils.log("INFO","url:"+url +"\nrequestBody:"+ requestBody,  isDebugEnabled)\r
279         APIResponse apiResponse = null\r
280         try{\r
281             RESTConfig config = new RESTConfig(url);\r
282             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");\r
283             apiResponse = client.httpPost(requestBody)\r
284             utils.log("INFO","response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString(),  isDebugEnabled)    \r
285             utils.log("INFO","======== Completed Execute VF-C adapter Post Process ======== ",  isDebugEnabled)\r
286         }catch(Exception e){\r
287             utils.log("ERROR","Exception occured while executing AAI Post Call. Exception is: \n" + e,  isDebugEnabled)\r
288             throw new BpmnError("MSOWorkflowException")\r
289         }        \r
290         return apiResponse\r
291     }\r
292 }\r