Springboot 2.0 upgrade
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / CreateVFCNSResource.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - SO
4  * ================================================================================
5  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
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 org.onap.so.client.aai.AAIObjectType
24 import org.onap.so.client.aai.entities.uri.AAIResourceUri
25 import org.onap.so.client.aai.entities.uri.AAIUriFactory;
26 import org.camunda.bpm.engine.delegate.BpmnError
27 import org.camunda.bpm.engine.delegate.DelegateExecution
28 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor 
29 import org.onap.so.bpmn.common.scripts.ExceptionUtil 
30 import org.onap.so.bpmn.core.json.JsonUtils
31 import org.onap.so.client.HttpClient
32 import org.onap.so.logger.MessageEnum
33 import org.onap.so.logger.MsoLogger
34 import org.onap.so.rest.APIResponse
35 import org.onap.so.rest.RESTClient 
36 import org.onap.so.rest.RESTConfig
37
38 import groovy.json.*
39
40 /**
41  * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process.
42  * flow for VFC Network Service Create
43  */
44 public class CreateVFCNSResource extends AbstractServiceTaskProcessor {
45         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateVFCNSResource.class);
46
47
48     String vfcUrl = "/vfc/rest/v1/vfcadapter"
49             
50     String host = "http://mso.mso.testlab.openecomp.org:8080"
51     
52     ExceptionUtil exceptionUtil = new ExceptionUtil()
53
54     JsonUtils jsonUtil = new JsonUtils()
55
56     /**
57      * CreateVFCNSResource
58      * Pre Process the BPMN Flow Request
59      * Inclouds:
60      * generate the nsOperationKey
61      * generate the nsParameters
62      */
63     public void preProcessRequest (DelegateExecution execution) {
64         JsonUtils jsonUtil = new JsonUtils()
65
66        String msg = ""
67        msoLogger.trace("preProcessRequest() ")
68        try {
69            //deal with nsName and Description
70            String resourceInput = execution.getVariable("resourceInput")
71
72            String resourceParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters")
73            // get service name
74            String resourceName = jsonUtil.getJsonValue(resourceInput, "resourceInstanceName")
75            execution.setVariable("nsServiceName", resourceName)
76
77            String nsServiceDescription = execution.getVariable("nsServiceDescription")
78            msoLogger.info("nsServiceName:" + resourceName + " nsServiceDescription:" + nsServiceDescription)
79            //deal with operation key
80            String globalSubscriberId = jsonUtil.getJsonValue(resourceInput, "globalSubscriberId")
81            msoLogger.info("globalSubscriberId:" + globalSubscriberId)
82            //set local globalSubscriberId variable
83            execution.setVariable("globalSubscriberId", globalSubscriberId);
84            String serviceType = execution.getVariable("serviceType")
85            msoLogger.info("serviceType:" + serviceType)
86
87            String serviceId = execution.getVariable("serviceInstanceId")
88            msoLogger.info("serviceId:" + serviceId)
89
90            String operationId = jsonUtil.getJsonValue(resourceInput, "operationId")
91            msoLogger.info("serviceType:" + serviceType)
92
93            String nodeTemplateUUID = jsonUtil.getJsonValue(resourceInput, "resourceModelInfo.modelCustomizationUuid")
94            String nsServiceModelUUID = jsonUtil.getJsonValue(resourceParameters, "requestInputs.nsd0_providing_service_uuid")
95            msoLogger.info("nodeTemplateUUID:" + nodeTemplateUUID)
96            /*
97             * segmentInformation needed as a object of segment
98             * {
99             *     "domain":"",
100             *     "nodeTemplateName":"",
101             *     "nodeType":"",
102             *     "nsParameters":{
103             *       //this is the nsParameters sent to VF-C
104             *     }
105             * }
106             */
107            String nsParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters")
108            msoLogger.info("nsParameters:" + nsParameters)
109            String nsOperationKey = """{
110                    "globalSubscriberId":"${globalSubscriberId}",
111                    "serviceType":"${serviceType}",
112                    "serviceId":"${serviceId}",
113                    "operationId":"${operationId}",
114                    "nodeTemplateUUID":"${nodeTemplateUUID}"
115                     }"""
116            execution.setVariable("nsOperationKey", nsOperationKey);
117            execution.setVariable("nsParameters", nsParameters)
118            execution.setVariable("nsServiceModelUUID", nsServiceModelUUID);
119            
120
121        } catch (BpmnError e) {
122            throw e;
123        } catch (Exception ex){
124            msg = "Exception in preProcessRequest " + ex.getMessage()
125            msoLogger.info(msg)
126            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
127        }
128        msoLogger.trace("Exit preProcessRequest ")
129         }
130
131     /**
132      * create NS task
133      */
134     public void createNetworkService(DelegateExecution execution) {
135         msoLogger.trace("createNetworkService ")
136         String nsOperationKey = execution.getVariable("nsOperationKey");
137         String nsServiceModelUUID = execution.getVariable("nsServiceModelUUID");
138         String nsParameters = execution.getVariable("nsParameters");
139         String nsServiceName = execution.getVariable("nsServiceName")
140         String nsServiceDescription = execution.getVariable("nsServiceDescription")
141         String locationConstraints = jsonUtil.getJsonValue(nsParameters, "locationConstraints")
142         String requestInputs = jsonUtil.getJsonValue(nsParameters, "requestInputs")
143         String reqBody ="""{
144                 "nsServiceName":"${nsServiceName}",
145                 "nsServiceDescription":"${nsServiceDescription}",
146                 "nsServiceModelUUID":"${nsServiceModelUUID}",
147                 "nsOperationKey":${nsOperationKey},
148                 "nsParameters":{
149                      "locationConstraints":${locationConstraints},
150                      "additionalParamForNs":${requestInputs}
151                 }
152                }"""
153         APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody)
154         String returnCode = apiResponse.getStatusCode()
155         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
156         String nsInstanceId = "";
157         if(returnCode== "200" || returnCode == "201"){
158             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")
159         }
160         execution.setVariable("nsInstanceId", nsInstanceId)
161         msoLogger.info(" *****Exit  createNetworkService *****")
162     }
163
164     /**
165      * instantiate NS task
166      */
167     public void instantiateNetworkService(DelegateExecution execution) {
168         msoLogger.trace("instantiateNetworkService ")
169         String nsOperationKey = execution.getVariable("nsOperationKey");
170         String nsParameters = execution.getVariable("nsParameters");
171         String nsServiceName = execution.getVariable("nsServiceName")
172         String nsServiceDescription = execution.getVariable("nsServiceDescription")
173         String reqBody ="""{
174         "nsServiceName":"${nsServiceName}",
175         "nsServiceDescription":"${nsServiceDescription}",
176         "nsOperationKey":${nsOperationKey},
177         "nsParameters":${nsParameters}
178        }"""
179         String nsInstanceId = execution.getVariable("nsInstanceId")
180         String url = host + vfcUrl + "/ns/" +nsInstanceId + "/instantiate"
181         APIResponse apiResponse = postRequest(execution, url, reqBody)
182         String returnCode = apiResponse.getStatusCode()
183         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
184         String jobId = "";
185         if(returnCode== "200"|| returnCode == "201"){
186             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
187         }
188         execution.setVariable("jobId", jobId)
189         msoLogger.info(" *****Exit  instantiateNetworkService *****")
190     }
191
192     /**
193      * query NS task
194      */
195     public void queryNSProgress(DelegateExecution execution) {
196         msoLogger.trace("queryNSProgress ")
197         String jobId = execution.getVariable("jobId")
198         String nsOperationKey = execution.getVariable("nsOperationKey");
199         String url = host + vfcUrl + "/jobs/" + jobId
200         APIResponse apiResponse = postRequest(execution, url, nsOperationKey)
201         String returnCode = apiResponse.getStatusCode()
202         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
203         String operationStatus = "error"
204         if(returnCode== "200"|| returnCode == "201"){
205             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
206         }
207         execution.setVariable("operationStatus", operationStatus)
208         msoLogger.info(" *****Exit  queryNSProgress *****")
209     }
210
211     /**
212      * delay 5 sec 
213      */
214     public void timeDelay(DelegateExecution execution) {
215         try {
216             Thread.sleep(5000);
217         } catch(InterruptedException e) {           
218             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Time Delay exception" + e , "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "");
219         }
220     }
221
222     /**
223      * finish NS task
224      */
225     public void addNSRelationship(DelegateExecution execution) {
226         msoLogger.trace("addNSRelationship ")
227         String nsInstanceId = execution.getVariable("nsInstanceId")
228         if(nsInstanceId == null || nsInstanceId == ""){
229             msoLogger.info(" create NS failed, so do not need to add relationship")
230             return
231         }
232         String globalSubscriberId = execution.getVariable("globalSubscriberId")
233         String serviceType = execution.getVariable("serviceType")
234         String serviceId = execution.getVariable("serviceInstanceId")
235
236         AAIResourceUri nsUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,nsInstanceId)
237         AAIResourceUri relatedServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,serviceId)
238
239         try{
240             getAAIClient().connect(nsUri,relatedServiceUri)
241             msoLogger.info("NS relationship to Service added successfully")
242         }catch(Exception e){
243             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while Creating NS relationship.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e.getMessage(),e);
244             throw new BpmnError("MSOWorkflowException")
245         }
246     }
247
248     /**
249      * post request
250      * url: the url of the request
251      * requestBody: the body of the request
252      */
253     private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){
254         msoLogger.trace("Started Execute VFC adapter Post Process ")
255         msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody)
256         APIResponse apiResponse = null
257         try{
258             RESTConfig config = new RESTConfig(url);
259             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");
260             apiResponse = client.httpPost(requestBody)
261             msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString())    
262             msoLogger.trace("Completed Execute VF-C adapter Post Process ")
263         }catch(Exception e){
264             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e);
265             throw new BpmnError("MSOWorkflowException")
266         }        
267         return apiResponse
268     }
269     
270         public void sendSyncResponse (DelegateExecution execution) {
271                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
272                 utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled)
273
274                 try {
275                         String operationStatus = execution.getVariable("operationStatus")
276                         // RESTResponse for main flow
277                         String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim()
278                         utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + resourceOperationResp, isDebugEnabled)
279                         sendWorkflowResponse(execution, 202, resourceOperationResp)
280                         execution.setVariable("sentSyncResponse", true)
281
282                 } catch (Exception ex) {
283                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
284                         utils.log("DEBUG", msg, isDebugEnabled)
285                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
286                 }
287                 utils.log("DEBUG"," ***** Exit sendSyncResopnse *****",  isDebugEnabled)
288         }
289
290 }