Merge "Support for SO to ExtAPI"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / UpdateNetworkInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. 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.apache.commons.lang3.*
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.common.scripts.MsoUtils
31 import org.onap.so.bpmn.core.WorkflowException
32 import org.onap.so.bpmn.core.json.JsonUtils
33 import org.slf4j.Logger
34 import org.slf4j.LoggerFactory
35
36 import groovy.json.*
37
38 /**
39  * This groovy class supports the <class>UpdateNetworkInstance.bpmn</class> process.
40  *
41  */
42 public class UpdateNetworkInstance extends AbstractServiceTaskProcessor {
43     private static final Logger logger = LoggerFactory.getLogger( UpdateNetworkInstance.class);
44         
45         String Prefix="UPDNI_"
46         ExceptionUtil exceptionUtil = new ExceptionUtil()
47         JsonUtils jsonUtil = new JsonUtils()
48
49         public InitializeProcessVariables(DelegateExecution execution){
50
51                 execution.setVariable(Prefix + "source", "")
52                 execution.setVariable(Prefix + "Success", false)
53
54                 execution.setVariable(Prefix + "CompleteMsoProcessRequest", "")
55                 execution.setVariable(Prefix + "FalloutHandlerRequest", "")
56
57         }
58
59
60         /**
61          * This method is executed during the preProcessRequest task of the <class>UpdateNetworkInstance.bpmn</class> process.
62          * @param execution
63          */
64
65         // **************************************************
66         //     Pre or Prepare Request Section
67         // **************************************************
68         /**
69          * This method is executed during the preProcessRequest task of the <class>UpdateNetworkInstance.bpmn</class> process.
70          * @param execution
71          */
72         public void preProcessRequest (DelegateExecution execution) {
73
74                 execution.setVariable("prefix",Prefix)
75
76                 logger.trace("Inside preProcessRequest() of UpdateNetworkInstance Request")
77
78                 try {
79                         // initialize flow variables
80                         InitializeProcessVariables(execution)
81
82                         String sdncVersion = execution.getVariable("sdncVersion")
83                         if (sdncVersion == null || sdncVersion == "1610") {
84                                 // 'a-la-cart' default, sdncVersion = '1610'
85                                 execution.setVariable("sdncVersion", "1610")
86                                 String bpmnRequest = execution.getVariable("bpmnRequest")
87                                 if (bpmnRequest != null) {                                        
88                                         String disableRollback = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.requestInfo.suppressRollback")
89                                         if (disableRollback != null) {
90                                            execution.setVariable("disableRollback", disableRollback)
91                                            logger.debug("Received 'suppressRollback': " + disableRollback )
92                                         } else {
93                                            execution.setVariable("disableRollback", false)
94                                         }   
95                                         logger.debug(" Set 'disableRollback' : " + execution.getVariable("disableRollback") )
96                                 } else {
97                                         String dataErrorMessage = " Invalid 'bpmnRequest' request."
98                                         logger.debug(dataErrorMessage)
99                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage)
100                                 }
101
102                         } else {
103                             // 'macro' TEST ONLY, sdncVersion = '1702'
104                             logger.debug(" \'disableRollback\' : " + execution.getVariable("disableRollback") )
105                         }
106
107                         String requestId = execution.getVariable("msoRequestId")
108                         if (requestId != null) {
109                                 execution.setVariable("mso-request-id", requestId)
110                         } else {
111                                 requestId = execution.getVariable("mso-request-id")
112                         }
113                         execution.setVariable(Prefix + "requestId", requestId)
114
115                         // get/set 'requestId'
116                         if (execution.getVariable("requestId") == null) {
117                                 execution.setVariable("requestId", requestId)
118                         }
119
120                         //Place holder for additional code.
121
122                         // TODO ???
123                         // userParams???  1) pre-loads indicator, 2) 'auto-activation'
124                         // Tag/Value parameters
125                         //
126                         // Map: 'networkInputParams': 'auto-activation''
127                         // Sample format?
128                         // "requestParameters": {
129                         //     "userParams": [
130             //          {
131                         //               "name": "someUserParam1",
132                         //               "value": "someValue1"
133                         //          }
134             //     ]
135                     //   }
136                         //
137                         // String userParams = //use json util to extract "userParams"//
138                 // execution.setVariable("networkInputParams", userParams)
139                         // else: execution.setVariable("networkInputParams", null)
140                         //
141
142                 } catch (BpmnError e) {
143                     throw e;
144
145                 } catch (Exception ex){
146                         sendSyncError(execution)
147                          // caught exception
148                         String exceptionMessage = "Exception Encountered in UpdateNetworkInstance, PreProcessRequest() - " + ex.getMessage()
149                         logger.debug(exceptionMessage)
150                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
151
152                 }
153         }
154
155         public void sendSyncResponse (DelegateExecution execution) {
156
157                 execution.setVariable("prefix",Prefix)
158
159                 logger.trace("Inside sendSyncResponse() of UpdateNetworkInstance")
160
161                 try {
162                         String requestId = execution.getVariable("mso-request-id")
163                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
164
165                         // RESTResponse (for API Handler (APIH) Reply Task)
166                         String updateNetworkRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
167
168                         logger.debug(" sendSyncResponse to APIH - " + "\n" + updateNetworkRestRequest)
169                         sendWorkflowResponse(execution, 202, updateNetworkRestRequest)
170
171                 } catch (Exception ex) {
172                         String exceptionMessage = "Bpmn error encountered in UpdateNetworkInstance flow. sendSyncResponse() - " + ex.getMessage()
173                         logger.debug(exceptionMessage)
174                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
175                 }
176
177         }
178
179
180         public void getNetworkModelInfo (DelegateExecution execution) {
181
182                 execution.setVariable("prefix", Prefix)
183
184                 logger.trace("Inside getNetworkModelInfo() of UpdateNetworkInstance")
185
186                 try {
187
188                         // For Ala-Carte (sdnc = 1610): 
189                         // 1. the Network ModelInfo is expected to be sent 
190                         //     via requestDetails.modelInfo (modelType = network), ex: modelCustomizationId
191                         // 2. the Service ModelInfo is expected to be sent but will be IGNORE 
192                         //     via requestDetails.relatedInstanceList.relatedInstance.modelInfo (modelType = service)
193                         
194                 } catch (Exception ex) {
195                         sendSyncError(execution)
196                    String exceptionMessage = "Bpmn error encountered in UpdateNetworkInstance flow. getNetworkModelInfo() - " + ex.getMessage()
197                    logger.debug(exceptionMessage)
198                    exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
199
200                 }
201
202         }
203
204
205         public void sendSyncError (DelegateExecution execution) {
206
207                 execution.setVariable("prefix", Prefix)
208
209                 logger.trace("Inside sendSyncError() of UpdateNetworkInstance")
210
211                 try {
212
213                         String requestId = execution.getVariable("mso-request-id")
214                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
215
216                         // REST Error (for API Handler (APIH) Reply Task)
217                         String syncError = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
218
219                         sendWorkflowResponse(execution, 500, syncError)
220
221                 } catch (Exception ex) {
222                         logger.debug(" Bpmn error encountered in UpdateNetworkInstance flow. sendSyncError() - " + ex.getMessage())
223                 }
224
225         }
226
227         public void prepareCompletion (DelegateExecution execution) {
228
229                 execution.setVariable("prefix",Prefix)
230
231                 logger.trace("Inside prepareCompletion() of UpdateNetworkInstance")
232
233                 try {
234
235                         String requestId = execution.getVariable("mso-request-id")
236                         String source = execution.getVariable(Prefix + "source")
237
238                         String msoCompletionRequest =
239                                 """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
240                                                                 xmlns:ns="http://org.onap/so/request/types/v1">
241                                                 <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
242                                                         <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
243                                                         <action>UPDATE</action>
244                                                         <source>VID</source>
245                                                 </request-info>
246                                                 <aetgt:status-message>Network has been updated successfully.</aetgt:status-message>
247                                                 <aetgt:mso-bpel-name>BPMN Network action: UPDATE</aetgt:mso-bpel-name>
248                                         </aetgt:MsoCompletionRequest>"""
249
250                                 // Format Response
251                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
252
253                         // normal path
254                         execution.setVariable(Prefix + "Success", true)
255                         execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest)
256                         logger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest)
257
258                 } catch (Exception ex) {
259                         String exceptionMessage = " Bpmn error encountered in UpdateNetworkInstance flow. prepareCompletion() - " + ex.getMessage()
260                         logger.debug(exceptionMessage)
261                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
262
263                 }
264
265
266         }
267
268
269
270
271         // **************************************************
272         //     Post or Validate Response Section
273         // **************************************************
274
275         public void postProcessResponse (DelegateExecution execution) {
276
277                 execution.setVariable("prefix", Prefix)
278
279                 logger.trace("Inside postProcessResponse() of UpdateNetworkInstance")
280
281                 try {
282
283                         if (execution.getVariable("CMSO_ResponseCode") == "200") {
284                                 execution.setVariable(Prefix + "Success", true)
285                                 logger.trace("UpdateNetworkInstance Success ")
286                                 //   Place holder for additional code.
287
288                          } else {
289                                 execution.setVariable(Prefix + "Success", false)
290                                 logger.trace("UpdateNetworkInstance Failed in CompletionMsoProces flow!. ")
291
292                          }
293
294
295                 } catch (Exception ex) {
296                         String exceptionMessage = " Bpmn error encountered in UpdateNetworkInstance flow. postProcessResponse() - " + ex.getMessage()
297                         logger.debug(exceptionMessage)
298                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage)
299
300             }
301
302         }
303
304
305         // *******************************
306         //     Build Error Section
307         // *******************************
308
309         public void processRollbackData (DelegateExecution execution) {
310
311                 execution.setVariable("prefix", Prefix)
312
313                 logger.trace("Inside processRollbackData() of UpdateNetworkInstance")
314
315                 try {
316                         //execution.getVariable("orchestrationStatus")
317                         //execution.getVariable("networkId")
318                         //execution.getVariable("networkName")
319                         //networkOutputParams
320                         //rollbackData
321                         //rolledBack
322
323                 } catch (Exception ex) {
324                         logger.debug(" Bpmn error encountered in UpdateNetworkInstance flow. callDBCatalog() - " + ex.getMessage())
325                 }
326
327         }
328
329         // Prepare for FalloutHandler
330         public void buildErrorResponse (DelegateExecution execution) {
331
332                 execution.setVariable("prefix", Prefix)
333                 
334                 logger.trace("Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler. ")
335                 
336                 String falloutHandlerRequest = ""
337                 String requestId = execution.getVariable("mso-request-id")
338
339                 try {
340                         
341                         WorkflowException wfe = execution.getVariable("WorkflowException")
342                         String errorCode = String.valueOf(wfe.getErrorCode())
343                         String errorMessage = wfe.getErrorMessage()
344                         falloutHandlerRequest =
345                                 """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
346                                                                      xmlns:ns="http://org.onap/so/request/types/v1"
347                                                                      xmlns:wfsch="http://org.onap/so/workflow/schema/v1">
348                                            <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
349                                               <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
350                                               <action>UPDATE</action>
351                                               <source>VID</source>
352                                            </request-info>
353                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
354                                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
355                                                         <aetgt:ErrorCode>${MsoUtils.xmlEscape(errorCode)}</aetgt:ErrorCode>
356                                                 </aetgt:WorkflowException>
357                                         </aetgt:FalloutHandlerRequest>"""
358
359                         logger.debug(falloutHandlerRequest)
360                         execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest)
361                         logger.debug("  Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest)
362
363                 } catch (Exception ex) {
364                         String errorException = "  Bpmn error encountered in UpdateNetworkInstance flow. FalloutHandlerRequest,  buildErrorResponse() - "
365                         logger.debug("Exception error in UpdateNetworkInstance flow,  buildErrorResponse(): {}", ex.getMessage(), ex)
366                         falloutHandlerRequest =
367                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1"
368                                                                      xmlns:ns="http://org.onap/so/request/types/v1"
369                                                                      xmlns:wfsch="http://org.onap/so/workflow/schema/v1">
370                                            <request-info xmlns="http://org.onap/so/infra/vnf-request/v1">
371                                               <request-id>${MsoUtils.xmlEscape(requestId)}</request-id>
372                                               <action>UPDATE</action>
373                                               <source>VID</source>
374                                            </request-info>
375                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
376                                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage>
377                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
378                                                 </aetgt:WorkflowException>
379                                         </aetgt:FalloutHandlerRequest>"""
380
381                         execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest)
382                         logger.debug("  Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest)
383
384                 }
385
386         }
387
388         public void processJavaException(DelegateExecution execution){
389
390                 execution.setVariable("prefix",Prefix)
391                 try{
392                         logger.debug("Caught a Java Exception in " + Prefix)
393                         logger.debug("Started processJavaException Method")
394                         logger.debug("Variables List: " + execution.getVariables())
395                         execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix)  // Adding this line temporarily until this flows error handling gets updated
396                         exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception")
397
398                 }catch(Exception e){
399                         logger.debug("Caught Exception during processJavaException Method: " + e)
400                         execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix)  // Adding this line temporarily until this flows error handling gets updated
401                         exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix)
402                 }
403                 logger.debug("Completed processJavaException Method in " + Prefix)
404         }
405
406 }