Springboot 2.0 upgrade
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / DoDeleteVFCNetworkServiceInstance.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.camunda.bpm.engine.delegate.BpmnError
24 import org.camunda.bpm.engine.delegate.DelegateExecution
25 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
26 import org.onap.so.bpmn.common.scripts.ExceptionUtil
27 import org.onap.so.bpmn.core.json.JsonUtils
28 import org.onap.so.client.aai.AAIObjectType
29 import org.onap.so.client.aai.entities.uri.AAIResourceUri
30 import org.onap.so.client.aai.entities.uri.AAIUriFactory
31 import org.onap.so.logger.MessageEnum
32 import org.onap.so.logger.MsoLogger
33 import org.onap.so.rest.APIResponse
34 import org.onap.so.rest.RESTClient
35 import org.onap.so.rest.RESTConfig
36
37 /**
38  * This groovy class supports the <class>DoDeleteVFCNetworkServiceInstance.bpmn</class> process.
39  * flow for E2E ServiceInstance Delete
40  */
41 public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProcessor {
42         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVFCNetworkServiceInstance.class);
43
44             
45     String vfcUrl = "/vfc/rest/v1/vfcadapter"
46     
47     String host = "http://mso.mso.testlab.openecomp.org:8080"
48     
49     ExceptionUtil exceptionUtil = new ExceptionUtil()
50
51     JsonUtils jsonUtil = new JsonUtils()
52
53     /**
54      * Pre Process the BPMN Flow Request
55      * Inclouds:
56      * generate the nsOperationKey
57      */
58     public void preProcessRequest (DelegateExecution execution) {
59
60         String msg = ""
61         msoLogger.trace("preProcessRequest() ")
62         try {
63             //deal with operation key
64             String globalSubscriberId = execution.getVariable("globalSubscriberId")
65             msoLogger.info("globalSubscriberId:" + globalSubscriberId)
66             String serviceType = execution.getVariable("serviceType")
67             msoLogger.info("serviceType:" + serviceType)
68             String serviceId = execution.getVariable("serviceId")
69             msoLogger.info("serviceId:" + serviceId)
70             String operationId = execution.getVariable("operationId")
71             msoLogger.info("serviceType:" + serviceType)
72             String nodeTemplateUUID = execution.getVariable("resourceTemplateId")
73             msoLogger.info("nodeTemplateUUID:" + nodeTemplateUUID)
74             String nsInstanceId = execution.getVariable("resourceInstanceId")
75             msoLogger.info("nsInstanceId:" + nsInstanceId)
76             execution.setVariable("nsInstanceId",nsInstanceId)
77             String nsOperationKey = """{
78             "globalSubscriberId":"${globalSubscriberId}",
79             "serviceType":"${serviceType}",
80             "serviceId":"${serviceId}",
81             "operationId":"${operationId}",
82             "nodeTemplateUUID":"${nodeTemplateUUID}"
83              }"""
84             execution.setVariable("nsOperationKey", nsOperationKey);
85             msoLogger.info("nsOperationKey:" + nsOperationKey)
86         } catch (BpmnError e) {
87             throw e;
88         } catch (Exception ex){
89             msg = "Exception in preProcessRequest " + ex.getMessage()
90             msoLogger.info(msg)
91             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
92         }
93         msoLogger.trace("Exit preProcessRequest ")
94         }
95
96     /**
97      * unwind NS from AAI relationship
98      */
99     public void deleteNSRelationship(DelegateExecution execution) {
100         def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
101         utils.log("INFO"," ***** deleteNSRelationship *****",  isDebugEnabled)
102         String nsInstanceId = execution.getVariable("resourceInstanceId")
103         if(nsInstanceId == null || nsInstanceId == ""){
104             utils.log("INFO"," Delete NS failed",  isDebugEnabled)
105             return
106         }
107         String globalSubscriberId = execution.getVariable("globalSubscriberId")
108         String serviceType = execution.getVariable("serviceType")
109         String serviceId = execution.getVariable("serviceId")
110         AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceId)
111         AAIResourceUri nsServiceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, nsInstanceId)
112         try {
113             getAAIClient().disconnect(serviceInstanceUri, nsServiceInstanceUri)
114         }catch(Exception e){
115             exceptionUtil.buildAndThrowWorkflowException(execution,25000,"Exception occured while NS disconnect call: " + e.getMessage())
116         }
117         utils.log("INFO"," *****Exit deleteNSRelationship *****",  isDebugEnabled)
118     }
119
120     /**
121      * delete NS task
122      */
123     public void deleteNetworkService(DelegateExecution execution) {
124
125         msoLogger.trace("deleteNetworkService  start ")
126         String nsOperationKey = execution.getVariable("nsOperationKey");
127         String url = host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId") 
128         APIResponse apiResponse = deleteRequest(execution, url, nsOperationKey)
129         String returnCode = apiResponse.getStatusCode()
130         String apiResponseAsString = apiResponse.getResponseBodyAsString()
131         String operationStatus = "error";
132         if(returnCode== "200" || returnCode== "202"){
133             operationStatus = "finished"
134         }
135         execution.setVariable("operationStatus", operationStatus)
136         
137         msoLogger.trace("deleteNetworkService  end ")
138     }
139
140     /**
141      * instantiate NS task
142      */
143     public void terminateNetworkService(DelegateExecution execution) {
144
145         msoLogger.trace("terminateNetworkService  start ")
146         String nsOperationKey = execution.getVariable("nsOperationKey") 
147         String url =  host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId") + "/terminate"
148         APIResponse apiResponse = postRequest(execution, url, nsOperationKey)
149         String returnCode = apiResponse.getStatusCode()
150         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
151         String jobId = "";
152         if(returnCode== "200" || returnCode== "202"){
153             jobId =  jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
154         }
155         execution.setVariable("jobId", jobId)   
156         msoLogger.trace("terminateNetworkService  end ")
157     }
158
159     /**
160      * query NS task
161      */
162     public void queryNSProgress(DelegateExecution execution) {
163
164         msoLogger.trace("queryNSProgress  start ")
165         String jobId = execution.getVariable("jobId")
166         String nsOperationKey = execution.getVariable("nsOperationKey");
167         String url =  host + vfcUrl + "/jobs/" +  execution.getVariable("jobId") 
168         APIResponse apiResponse = postRequest(execution, url, nsOperationKey)
169         String returnCode = apiResponse.getStatusCode()
170         String apiResponseAsString = apiResponse.getResponseBodyAsString()
171         String operationProgress = "100"
172         if(returnCode== "200"){
173             operationProgress = jsonUtil.getJsonValue(apiResponseAsString, "responseDescriptor.progress")
174         }
175         execution.setVariable("operationProgress", operationProgress)
176         msoLogger.trace("queryNSProgress  end ")
177     }
178
179     /**
180      * delay 5 sec 
181      */
182     public void timeDelay(DelegateExecution execution) {
183         try {
184             Thread.sleep(5000);
185         } catch(InterruptedException e) {           
186             msoLogger.info("Time Delay exception" + e)
187         }
188     }
189
190     /**
191      * finish NS task
192      */
193     public void finishNSDelete(DelegateExecution execution) {
194         //no need to do anything util now
195     }
196
197     /**
198      * post request
199      * url: the url of the request
200      * requestBody: the body of the request
201      */
202     private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){
203
204         msoLogger.trace("Started Execute VFC adapter Post Process ")
205         msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody)
206         APIResponse apiResponse = null
207         try{
208             RESTConfig config = new RESTConfig(url);
209             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");;
210             apiResponse = client.httpPost(requestBody)
211             msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString())
212             msoLogger.trace("Completed Execute VF-C adapter Post Process ")
213         }catch(Exception e){
214             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VF-C Post Call. Exception is: \n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e);
215             throw new BpmnError("MSOWorkflowException")
216         }        
217         return apiResponse
218     }
219     /**
220      * delete request
221      * url: the url of the request
222      * requestBody: the body of the request
223      */
224     private APIResponse deleteRequest(DelegateExecution execution, String url, String requestBody){
225
226         msoLogger.trace("Started Execute VFC adapter Delete Process ")       
227         msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody)
228         APIResponse apiResponse = null
229         try{
230             RESTConfig config = new RESTConfig(url);
231             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");
232             apiResponse = client.httpDelete(requestBody)
233             msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) 
234             msoLogger.trace("Completed Execute VF-C adapter Delete Process ") 
235         }catch(Exception e){
236             msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VF-C Post Call. Exception is: \n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); 
237             throw new BpmnError("MSOWorkflowException")
238         }        
239         return apiResponse
240     }
241 }