Springboot 2.0 upgrade
[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  * 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 DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProcessor {
45         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVFCNetworkServiceInstance.class);
46
47     String vfcUrl = "/vfc/rest/v1/vfcadapter"
48             
49     String host = "http://mso.mso.testlab.openecomp.org:8080"
50     
51     ExceptionUtil exceptionUtil = new ExceptionUtil()
52
53     JsonUtils jsonUtil = new JsonUtils()
54
55     /**
56      * Pre Process the BPMN Flow Request
57      * Inclouds:
58      * generate the nsOperationKey
59      * generate the nsParameters
60      */
61     public void preProcessRequest (DelegateExecution execution) {
62        String msg = ""
63        msoLogger.trace("preProcessRequest()")
64        try {
65            //deal with nsName and Description
66            String nsServiceName = execution.getVariable("nsServiceName")
67            String nsServiceDescription = execution.getVariable("nsServiceDescription")
68            msoLogger.debug("nsServiceName:" + nsServiceName + " nsServiceDescription:" + nsServiceDescription)
69            //deal with operation key
70            String globalSubscriberId = execution.getVariable("globalSubscriberId")
71            msoLogger.debug("globalSubscriberId:" + globalSubscriberId)
72            String serviceType = execution.getVariable("serviceType")
73            msoLogger.debug("serviceType:" + serviceType)
74            String serviceId = execution.getVariable("serviceId")
75            msoLogger.debug("serviceId:" + serviceId)
76            String operationId = execution.getVariable("operationId")
77            msoLogger.debug("serviceType:" + serviceType)
78            String nodeTemplateUUID = execution.getVariable("resourceUUID")
79            msoLogger.debug("nodeTemplateUUID:" + nodeTemplateUUID)
80            /*
81             * segmentInformation needed as a object of segment
82             * {
83             *     "domain":"",
84             *     "nodeTemplateName":"",
85             *     "nodeType":"",
86             *     "nsParameters":{
87             *       //this is the nsParameters sent to VF-C
88             *     }
89             * }
90             */
91            String nsParameters = execution.getVariable("resourceParameters")
92            msoLogger.debug("nsParameters:" + nsParameters)
93            String nsOperationKey = """{
94                    "globalSubscriberId":"${globalSubscriberId}",
95                    "serviceType":"${serviceType}",
96                    "serviceId":"${serviceId}",
97                    "operationId":"${operationId}",
98                    "nodeTemplateUUID":"${nodeTemplateUUID}"
99                     }"""
100            execution.setVariable("nsOperationKey", nsOperationKey);
101            execution.setVariable("nsParameters", nsParameters)
102            
103
104        } catch (BpmnError e) {
105            throw e;
106        } catch (Exception ex){
107            msg = "Exception in preProcessRequest " + ex.getMessage()
108            msoLogger.debug(msg)
109            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
110        }
111        msoLogger.trace("Exit preProcessRequest")
112         }
113
114     /**
115      * create NS task
116      */
117     public void createNetworkService(DelegateExecution execution) {
118         msoLogger.trace("createNetworkService")
119         String nsOperationKey = execution.getVariable("nsOperationKey");
120         String nsParameters = execution.getVariable("nsParameters");
121         String nsServiceName = execution.getVariable("nsServiceName")
122         String nsServiceDescription = execution.getVariable("nsServiceDescription")
123         String reqBody ="""{
124                 "nsServiceName":"${nsServiceName}",
125                 "nsServiceDescription":"${nsServiceDescription}",
126                 "nsOperationKey":${nsOperationKey},
127                 "nsParameters":${nsParameters}
128                }"""
129         APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody)
130         String returnCode = apiResponse.getStatusCode()
131         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
132         String nsInstanceId = "";
133         if(returnCode== "200" || returnCode == "201"){
134             nsInstanceId =  jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId")
135         }
136         execution.setVariable("nsInstanceId", nsInstanceId)
137         msoLogger.trace("Exit  createNetworkService")
138     }
139
140     /**
141      * instantiate NS task
142      */
143     public void instantiateNetworkService(DelegateExecution execution) {
144         msoLogger.trace("instantiateNetworkService")
145         String nsOperationKey = execution.getVariable("nsOperationKey");
146         String nsParameters = execution.getVariable("nsParameters");
147         String nsServiceName = execution.getVariable("nsServiceName")
148         String nsServiceDescription = execution.getVariable("nsServiceDescription")
149         String reqBody ="""{
150         "nsServiceName":"${nsServiceName}",
151         "nsServiceDescription":"${nsServiceDescription}",
152         "nsOperationKey":${nsOperationKey},
153         "nsParameters":${nsParameters}
154        }"""
155         String nsInstanceId = execution.getVariable("nsInstanceId")
156         String url = host + vfcUrl + "/ns/" +nsInstanceId + "/instantiate"
157         APIResponse apiResponse = postRequest(execution, url, reqBody)
158         String returnCode = apiResponse.getStatusCode()
159         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
160         String jobId = "";
161         if(returnCode== "200"|| returnCode == "201"){
162             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
163         }
164         execution.setVariable("jobId", jobId)
165         msoLogger.trace("Exit  instantiateNetworkService")
166     }
167
168     /**
169      * query NS task
170      */
171     public void queryNSProgress(DelegateExecution execution) {
172         msoLogger.trace("queryNSProgress")
173         String jobId = execution.getVariable("jobId")
174         String nsOperationKey = execution.getVariable("nsOperationKey");
175         String url = host + vfcUrl + "/jobs/" + jobId
176         APIResponse apiResponse = postRequest(execution, url, nsOperationKey)
177         String returnCode = apiResponse.getStatusCode()
178         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
179         String operationStatus = "error"
180         if(returnCode== "200"|| returnCode == "201"){
181             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
182         }
183         execution.setVariable("operationStatus", operationStatus)
184         msoLogger.trace("Exit  queryNSProgress")
185     }
186
187     /**
188      * delay 5 sec 
189      */
190     public void timeDelay(DelegateExecution execution) {
191         try {
192             Thread.sleep(5000);
193         } catch(InterruptedException e) {           
194            msoLogger.debug("Time Delay exception" + e )
195         }
196     }
197
198     /**
199      * finish NS task
200      */
201     public void addNSRelationship(DelegateExecution execution) {
202         msoLogger.trace("addNSRelationship")
203         String nsInstanceId = execution.getVariable("nsInstanceId")
204         if(nsInstanceId == null || nsInstanceId == ""){
205             msoLogger.debug(" create NS failed, so do not need to add relationship")
206             return
207         }
208         String globalSubscriberId = execution.getVariable("globalSubscriberId")
209         String serviceType = execution.getVariable("serviceType")
210         String serviceId = execution.getVariable("serviceId")
211
212         AAIResourceUri nsUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,nsInstanceId)
213         AAIResourceUri relatedServiceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE,globalSubscriberId,serviceType,serviceId)
214
215         try{
216             getAAIClient().connect(nsUri,relatedServiceUri)
217             msoLogger.info("NS relationship to Service added successfully")
218         }catch(Exception e){
219             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
220             throw new BpmnError("MSOWorkflowException")
221         }
222     }
223
224     /**
225      * post request
226      * url: the url of the request
227      * requestBody: the body of the request
228      */
229     private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){
230         msoLogger.trace("Started Execute VFC adapter Post Process")
231         msoLogger.debug("url:"+url +"\nrequestBody:"+ requestBody)
232         APIResponse apiResponse = null
233         try{
234             RESTConfig config = new RESTConfig(url);
235             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");
236             apiResponse = client.httpPost(requestBody)
237             msoLogger.debug("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString())    
238             msoLogger.trace("Completed Execute VF-C adapter Post Process")
239         }catch(Exception e){
240                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
241             throw new BpmnError("MSOWorkflowException")
242         }        
243         return apiResponse
244     }
245 }